On Mon, 19 Nov 2007 09:15:26 +0100, FFMG <FFMG.30aezy@no-mx.httppoint.com
wrote:
Quote:
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 am
not getting the same behavior across the versions.
>
// Some simple code/
<?php
class TestClass
{
function TestClass() // For php4
{
$this->__construct();
}
>
var $_classValue = '';
function __construct()// For php5 && 4
{
global $globalValue;
$globalValue = $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 =& $this;
}
}
class bar{
function bar(){
$GLOBALS['b'] =& $this;
}
}
$a = $b = null;
new foo();
var_dump($a);
new bar();
var_dump($b);
?>
As the manual states:
"Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus
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'].
Quote:
// I use a random to make certain we are talking about the same
class.
$this->_classValue = 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 constructing
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'] = clone $this;
$this->test = 'hello';
$GLOBALS['b'] = clone $this;
}
}
$a = $b = 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