|
Posted by Rik Wasmus on 11/19/07 17:57
On Mon, 19 Nov 2007 09:15:26 +0100, FFMG <FFMG.30aezy@no-mx.httppoint.co=
m> =
wrote:
> I am slowly moving my code to php5.
> But I would like to make it backward compatible in case something bad
> happens, (and to make sure I understand what the changes are).
>
> The way the constructors work seem to have changed quite a bit and I a=
m
> not getting the same behavior across the versions.
>
> // Some simple code/
> <?php
> class TestClass
> {
> function TestClass() // For php4
> {
> $this->__construct();
> }
>
> var $_classValue =3D '';
> function __construct()// For php5 && 4
> {
> global $globalValue;
> $globalValue =3D $this;
While in PHP5 $globalValue now has a _reference_ to $this, in PHP4 =
$globalValue will have a _copy_ of $this.
There is another error: you should use the $GLOBALS array here, see =
<http://nl2.php.net/manual/en/language.references.whatdo.php>, and check=
=
this example (PHP4 compliant):
<?php
class foo{
function foo(){
global $a;
$a =3D& $this;
}
}
class bar{
function bar(){
$GLOBALS['b'] =3D& $this;
}
}
$a =3D $b =3D null;
new foo();
var_dump($a);
new bar();
var_dump($b);
?>
As the manual states:
"Think about global $var; as a shortcut to $var =3D& $GLOBALS['var'];. T=
hus =
assigning other reference to $var only changes the local variable's =
reference."
So, as soon as you make $a in this example a reference to whatever you =
want, it no longer references $GLOBALS['a'].
> // I use a random to make certain we are talking about the same
> class.
> $this->_classValue =3D md5(uniqid(mt_rand()));
^^And this code will not be performed in you copy of $this, as it is a =
copy no constructor code will be performed, expecially this particular =
code. Never ever copy (default for PHP4) your object it your constructin=
g =
is not even done (and actually, don't create a reference (default for =
PHP5) to your object untill it is done to be sure...). Example how this =
=
would work in PHP4 translated to PHP5:
<?php
class bar{
public $test;
function __construct(){
echo 'constructing';
$GLOBALS['a'] =3D clone $this;
$this->test =3D 'hello';
$GLOBALS['b'] =3D clone $this;
}
}
$a =3D $b =3D null;
var_dump(new bar(),$a,$b);
?>
Realize:
- we have three different objects here.
- the constructor is called only once, for our first 'anonymous' object.=
- bar::test will not be set in $a as the code never gets there for that =
=
object.
-- =
Rik Wasmus
[Back to original message]
|