rubing Posted November 22, 2008 Share Posted November 22, 2008 I was RTFMing today reading up on basic classes, when i came accross this users post to the php manual: If you just want to create a new object that extends another object and you want to copy all variables from the father object, you may use this piece of code: <?php $father =& new father(); $father->a_var = "Hello World."; $son = new son($event); $son->say_hello(); class father { public $a_var; } class son extends father { public function __construct($father_class) { foreach ($father_class as $variable=>$value) { $this->$variable = $value; } } public function say_hello() { echo "Son says: ".$this->a_var; } } ?> This outputs: Son says: Hello World. I copied and pasted his script, but it did not work. Then I figured that he must mean to replace $father_class with the actual instance name of the father class object. So, I replaced $father_class with just $father. Php issues the warning: Warning: Invalid argument supplied for foreach() in /home/bob/public_html/dirtrag.com/public/test.php on line 15 Finally, I said to myself: self: why does this dude have the ampersand (&) in his code: $father =& new father(); so, I tried removing the ampersand. still it does not work. ??? ??? Quote Link to comment https://forums.phpfreaks.com/topic/133786-copying-variables-from-parent/ Share on other sites More sharing options...
corbin Posted November 22, 2008 Share Posted November 22, 2008 In PHP4, the ampersand was used to denote a reference to the class, therefore, the class would be passed by reference later. $father =& new father(); $father->a_var = "Hello World."; $son = new son($event); Should actually be: $father =& new father(); $father->a_var = "Hello World."; $son = new son($father); I'm not sure when you would ever want to instantiate a child instance with the variables from a father instance. Quote Link to comment https://forums.phpfreaks.com/topic/133786-copying-variables-from-parent/#findComment-696372 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.