Jump to content

[SOLVED] Passing from parent class to all children


stuartmarsh

Recommended Posts

Does anybody know if it is possible to create new variables/functions on the fly in a parent class and have it pass down to all created children?  From my experience only the last created child will receive the change.

Take a look at this code to see what I mean:

<?PHP
class Dad {
private static $instance;

function __construct() {
	self::$instance =& $this;
}

public static function &get_instance() 
{
	return self::$instance;
}

function foo() {
	echo "foo<br />";
}
}

function &get_instance() {
return Dad::get_instance();
}

class Child1 extends Dad {
function bar1() {
	echo "Bar1<br />";
}
}

class Child2 extends Dad {
function bar2() {
	echo "Bar2<br />";
}
}

$Kid =& new Child1();
$Kid->foo();
$Kid->bar1();

$Kid2 =& new Child2();
$Kid2->foo();

echo "<hr>";
$base =& get_instance();
$base->newVar = "Bar";

var_dump($Kid);
var_dump($Kid2);
?>

When I add newVar to the parent class, it is only passed to $Kid2.

How can I make it so that both $Kid and $Kid2 get the new variable?

Is it even possible?

Link to comment
Share on other sites

Take a look at this code. I have just wrote it..

 

<?php

class ParentClass {
    
    static protected $objects;
    
    public function __construct()
    {
        self::$objects = array();
    }
    
    public function __get($name)
    {
        if (key_exists($name, self::$objects)) {
        	return self::$objects[$name];
        }
    }
    
    public function __set($name, $value)
    {
        self::$objects[$name] = $value;
    }
    
}

class ChildClass extends ParentClass  {
    
    public function __construct()
    {
        parent::__construct();
    }
    
    public function __get($name)
    {
        if (key_exists($name, parent::$objects)) {
        	return parent::$objects[$name];
        }
    }
    
    public function __set($name, $value)
    {
        parent::$objects[$name] = $value;
    }
}

$parent = new ParentClass();
$child = new ChildClass();
$secondChild = new ChildClass();

$parent->user = "c0d3r";
echo $child->user;
echo $secondChild->user;

?>

This is doing exactly what you want...

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.