开发者

PHP: just saying $someVariable; inside a function - does this do anything

开发者 https://www.devze.com 2023-02-28 01:13 出处:网络
I\'m working on some PHP code (that I didn\'t write). Here and there inside functions there\'s stuff like this:

I'm working on some PHP code (that I didn't write). Here and there inside functions there's stuff like this:

$foo;

if ($someCondition) {
    $foo="some value";
}
return $foo;

Just checking: that first $foo;开发者_运维问答 on a line by itself - it has no effect whatsoever, right?


This is debug code left over from PHP3 or PHP4. These versions generated an E_NOTICE for just mentioning a variable (it was implicitly a read access):

$undef;   // E_NOTICE

PHP5 however does not treat it as variable access anymore. So it goes ignored.


PHP3: Warning: Uninitialized variable or array index or property (undef)

PHP4: Notice: Undefined variable: undef

PHP5: silence


Your right. Maybe original developer come from another language and "declare" used vars.

Another way to write this code snippet is

if ($someCondition) {
    return "some value";
}

return null;


It would have some impact if it were:

global $foo;

But in the form you posted, it is irrelevant.


Right, no need for it at all. Some languages require a variable to be declared, not PHP.

In PHP, you can even concatenate into an undeclared variable. PHP is the loose hipster of the programming world. Anything goes, man.


I would guess it's lazy instantiation. I'd change the line to $foo = "", which should have the same effect;


I wonder if they think that its the equivalent to defining a variable to prevent errors when strict error reporting is enabled - although it actually doesn't (define the variable) when its written like that

0

精彩评论

暂无评论...
验证码 换一张
取 消