Jump to content

copying variables from parent


rubing

Recommended Posts

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. 

 

??? ???

Link to comment
https://forums.phpfreaks.com/topic/133786-copying-variables-from-parent/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.