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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.