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();
$Kid2->bar2();

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

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

When I add newVar to the parent class using an instance, it is only passed to $Kid2.
How can I make it so that both $Kid and $Kid2 get the new variable?

    You can maybe use a static variable to achieve this. Read this.

      This is a cheeky way of doing what you want with the magic methods get and set

      <?php
      class Dad
      {
      	public static $varPot = array();
      
      function __set($var, $val)
      {
      	self::$varPot[$var] = $val;
      }
      
      function __get($var)
      {
      	if (array_key_exists($var, self::$varPot))
      	{
      		return self::$varPot[$var];
      	}
      
      	echo "There is nothing for you here called $var<br />";
      }
      }
      
      class KidA extends Dad
      {
      	public $name = 'Tony';
      
      function foo()
      {
      	echo "FOOOOOOOOOO<br />";
      }
      }
      
      class KidB extends Dad
      {
      	public $name = 'Spencer';
      
      function bar()
      {
      	echo "BAAAAAAHHHHHH<br />";
      }
      }
      
      
      $kid1 = new KidA;
      
      $kid2 = new KidB;
      
      $kid1->like = 'Ice cream<br />';
      
      echo $kid2->like;
      
      $kid2->hate = 'innoculations<br />';
      
      echo $kid1->hate;
      ?>

      You might actually want to set up accessor methods to setting and getting properties if you don't want the PhPolice to come screaming at you wanting to make this more in the spirit of object orientatednessness. And for fun have a play with setting the name property, then echoing. This should teach you something.

        I just hope I never have to debug/maintain any code that depends on all these references and sharing of dynamic variables. :eek:

          Same here... that is pure voodoo. Well sort of, it's just avoidance of a more obvious route.

            I think most of those references are a reluctance to kick the PHP 4 habit. Unless they were getting stuck in there to try and make this work.

              Write a Reply...