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?

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

What you want to implement is an Observer Pattern[1]. Here's a reference implementation in Python.

 

It should port over quite easily for PHP. If you need any assistance or have any additional questions, I'll be happy to answer them.

 

[1]: http://en.wikipedia.org/wiki/Observer_Pattern#Python

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.