Difference between $ foo [bar] and $ foo ['bar'] in php

I used $foo[bar]for a large number of projects without noticing the missing

Currently, I understand why this works, I assume that this is due to the fact that the missing constant is replaced by its name, therefore it refers to the same element in the array.

But .. This is very wrong or can be taken. What are the disadvantages? Do I have to dig old projects to replace this or is the performance drop really not noticeable on this?

+4
source share
3 answers

What are the disadvantages?

Say that you have a URL, such as http://somesite.com/test.php?item=20,

Scenario: 1 (your case)

<?php
echo $_GET[item]; // 20 is printed with a warning.. 

: 2 ( )

<?php
define('item',20);
echo $_GET[item]; // A warning will be thrown and nothing will be printed.

, ? ?

.

+5

,

: undefined bar - "bar" [...] [...] on line

$foo[bar]

,

$arr1 = array(1=>1);
$arr2 = array(a=>2);
$arr3 = array('a'=>3);

print_r($arr1);
print_r($arr2);
print_r($arr3);

, , .

+2

$foo[bar] bar , $foo ['bar'] bar

$foo[bar] = "a";

Notice: Use of undefined constant bar - assumed 'bar' in [some_path] on line 5

, bar ,

decare bar

define("bar", 10);
$foo[bar] = "a";
echo $foo[bar]; // will display 10
+2

Source: https://habr.com/ru/post/1525407/


All Articles