PapaFreud
PapaFreud

Reputation: 3888

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

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?

Upvotes: 2

Views: 102

Answers (6)

mario
mario

Reputation: 145482

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

Upvotes: 1

robjmills
robjmills

Reputation: 18598

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

Upvotes: 0

trickwallett
trickwallett

Reputation: 2468

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

Upvotes: 0

Mild Fuzz
Mild Fuzz

Reputation: 30751

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.

Upvotes: 0

Yoshi
Yoshi

Reputation: 54659

It would have some impact if it were:

global $foo;

But in the form you posted, it is irrelevant.

Upvotes: 0

Bil
Bil

Reputation: 543

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;

Upvotes: 0

Related Questions