Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dynamic class extending

Tags:

oop

php

I know you can extend a class when constructing it like the following:

class b extends a {
}

But is it possible to dynamically extend classes from the scripts? Such as:

$b = new b($input) extends a;

What I wish to accomplish is to extend the module differnetly wheither it's used in admin rather than the public pages. I know I can create two different parent classes by the same name and only include one per admin or public. But my question is, is it possible to do it dynamically in PHP?

like image 413
tim Avatar asked Oct 25 '25 03:10

tim


1 Answers

No, not without an extension like RunKit.

You might consider an alternative approach. If you want B to assume the functionality of A, perhaps something like the following could provide a sort of "mixin" approach. The general picture is that, instead of B being a child of A, B delegates to A.

<?php

class MixMeIn
{
  public $favouriteNumber = 7;

  public function sayHi() {
    echo "Hello\n";
  }
}

class BoringClass
{
  private $mixins = array();

  public function mixin($object)
  {
    $this->mixins[] = $object;
  }

  public function doNothing() {
    echo "Zzz\n";
  }

  public function __call($method, $args)
  {
    foreach ($this->mixins as $mixin)
    {
      if (method_exists($mixin, $method))
      {
        return call_user_func_array(array($mixin, $method), $args);
      }
    }
    throw new Exception(__CLASS__ + " has no method " + $method);
  }

  public function __get($attr)
  {
    foreach ($this->mixins as $mixin)
    {
      if (property_exists($mixin, $attr))
      {
        return $mixin->$attr;
      }
    }
    throw new Exception(__CLASS__ + " has no property " + $attr);
  }

  public function __set($attr, $value)
  {
    foreach ($this->mixins as $mixin)
    {
      if (property_exists($mixin, $attr))
      {
        return $mixin->$attr = $value;
      }
    }
    throw new Exception(__CLASS__ + " has no property " + $attr);
  }

}

// testing

$boring = new BoringClass();
$boring->doNothing();
try {
  $boring->sayHi(); // not available :-(
}
catch (Exception $e) {
  echo "sayHi didn't work: ", $e->getMessage(), "\n";
}
// now we mixin the fun stuff!
$boring->mixin(new MixMeIn());
$boring->sayHi(); // works! :-)
echo $boring->favouriteNumber;

Just a zany idea. I hope I understood the question correctly.

like image 76
erisco Avatar answered Oct 27 '25 17:10

erisco