Understanding PHP5's Object Model
Posted: Wed Apr 28, 2010 12:25 am
Hi,
I need some education....
Assume a function SetGlob that sets a global variable, and a function GetGlob that returns its value.
Now look at this code:
In PHP4 it works the same regardless or whether $foo is a scalar or object. The first output and second output are identical.
In PHP5, the behaviour differs depending on whether $foo is an object or a scalar. If it's a scalar, then it works the same as PHP4. If it's an object, it works differently (different output).
Can someone please explain why that change in PHP's object model (from PHP4 to PHP5) was a good idea?
Here's the actual code along with results:
Results in PHP4:
Results in PHP5:
How can that possibly be a sensible change to the semantics of the language?
regards,
RR
I need some education....
Assume a function SetGlob that sets a global variable, and a function GetGlob that returns its value.
Now look at this code:
Code: Select all
// code that creates a variable called $foo
SetGlob($foo);
echo GetGlob();
// code that changes $foo
echo GetGlob();
In PHP5, the behaviour differs depending on whether $foo is an object or a scalar. If it's a scalar, then it works the same as PHP4. If it's an object, it works differently (different output).
Can someone please explain why that change in PHP's object model (from PHP4 to PHP5) was a good idea?
Here's the actual code along with results:
Code: Select all
<?php
class Holder
{
var $value;
function Holder($value)
{
$this->value = $value;
}
};
function SetGlob($var)
{
global $GlobVar;
$GlobVar = $var;
}
function GetGlob()
{
global $GlobVar;
if (is_object($GlobVar))
return ($GlobVar->value);
else
return ($GlobVar);
}
$str = "foo";
SetGlob($str);
echo "<p>Expecting 'foo': ".GetGlob();
$str = "bar";
echo "<p>Expecting 'foo': ".GetGlob();
$foo = new Holder("foo");
SetGlob($foo);
echo "<p>Expecting 'foo': ".GetGlob();
$foo->value = "bar";
echo "<p>Expecting 'foo': ".GetGlob();
?>
Code: Select all
Expecting 'foo': foo
Expecting 'foo': foo
Expecting 'foo': foo
Expecting 'foo': foo
Code: Select all
Expecting 'foo': foo
Expecting 'foo': foo
Expecting 'foo': foo
Expecting 'foo': bar
regards,
RR