PHP dynamic class

I know that you can extend a class when you create it like this:

class b extends a {
}

But is it possible to dynamically extend classes from scripts? For instance:

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

What I want to accomplish is to expand the module in different ways if it is used in the admin and not in the public pages. I know that I can create two different parent classes with the same name and include only one user or administrator. But my question is: is it possible to do this dynamically in PHP?

+3
source share
7 answers

You cannot, but this has been requested for several years: https://bugs.php.net/bug.php?id=41856&edit=1

You can define classes within eval, but this is more of a problem than declaring a class normally.

+2

, , RunKit.

. , B A, , - "mixin". , B, A, B 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;

. , .

+3

extends . extends , "" .

+1

, javascript :

<? //PHP 5.4+
final class ExpandoLookalike {
    //Allow callable properties to be executed
    public function __call($name, $arguments) {
        \call_user_func_array($this->$name, $arguments);
    }
}

$newBaseModule = static function(){
  $base = new ExpandoLookalike();
  //Common base functions get assigned here.
  $basePrivateVar = 42;

  $base->commonFunction = static function($params1, $params2) use ($basePrivateVar){
      echo "common function\n";
  };
  $base->comment = static function() use ($basePrivateVar){
    echo "Doing base comment with $basePrivateVar\n";
  };
  return $base;
};

//Javascript-style extends
$newAdminModule = static function($param) use ($newBaseModule){
  $base = $newBaseModule();

  $privateVar = 5;


  $base->adminProperty = 60;
  $base->suspendSite = static function() use ($param, $privateVar){
    echo 'Doing admin only function ';
    echo "with $param, $privateVar\n";

  };

  return $base;
};


$newPublicModule = static function() use ($newBaseModule){
  $base = $newBaseModule();

  $privateVar = 3;

  //Javascript-style overloading
  $oldComment = $base->comment;
  $base->comment = static function($data) use ($oldComment, $privateVar){
    $oldComment();
    echo 'Doing public function ';
    echo "with $data\n";
  };

  return $base;
};

$baseModule = $newBaseModule();
$adminModule = $newAdminModule('P');
$publicModule = $newPublicModule();

$adminModule->suspendSite(); //echos 'Doing admin only function with P, 5'
echo "{$adminModule->adminProperty}\n"; //echos '60'
$publicModule->comment('com'); //echos 'Doing base comment with 42'
                                     //'Doing public function with com'
?>

, :

<? //PHP 5.4+

$inheritAllTheThings = static function(){
  $base = new ExpandoLookalike();
  foreach(\func_get_args() as $object){
    foreach($object as $key => $value){
        //Properties from later objects overwrite properties from earlier ones.
        $base->$key = $value;
    }
  }
  return $base;
};

$allOfEm = $inheritAllTheThings(
  $newPublicModule(),
  $newAdminModule('Q'),
  ['anotherProp' => 69,]
);

$allOfEm->comment('f'); //echos 'Doing base comment with 42'
//Because AdminModule came after PublicModule, the function that echos 'f'
//from PublicModule was overridden by the function from AdminModule.
//Hence, order denotes resolutions for multiple inheritance collisions.
$allOfEm->suspendSite(); //echos 'Doing admin only function with Q, 5'
echo $allOfEm->anotherProp . "\n"; //echos '69'

?>
+1

. a b,

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

, .

0

, , . .

:

class a {
}
class b {
   public $object;
}

class bextendeda extends a {
}

b , .

class b {
    public $object;

    public function __contruct($extend = false) {
        if($extend) $this -> object = new bextendeda(); 
        else $this -> object = $this;
    }

    function __get($prop) {
        return $this-> object -> $prop;
    }

    function __set($prop, $val) {
       $this-> object -> $prop = $val;
    }
    function __call($name, $arguments)
    {
        return call_user_func_array(array($this -> object, $name), $arguments);
    }

}

, ,

$b = new b(true);

$b = new b();

:)

0

All Articles