PHP动态类扩展

时间:2012-05-06 05:13:14

标签: php oop

我知道您可以在构建类时扩展类,如下所示:

class b extends a {
}

但是可以从脚本中动态扩展类吗?如:

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

我希望实现的是在管理员而不是公共页面中使用它时,扩展模块。我知道我可以使用相同的名称创建两个不同的父类,并且每个管理员或公共只包含一个。但我的问题是,是否有可能在PHP中动态执行它?

7 个答案:

答案 0 :(得分:3)

不,没有像RunKit这样的扩展程序。

您可以考虑另一种方法。如果你想让B承担A的功能,也许像下面这样的东西可以提供一种“mixin”方法。总体情况是,B代表A代替B,而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;

只是一个滑稽的想法。我希望我能正确理解这个问题。

答案 1 :(得分:2)

你不能,但这已被要求几年:https://bugs.php.net/bug.php?id=41856&edit=1

您可以在eval中定义类,但比正常声明类更麻烦。

答案 2 :(得分:1)

但是在创建对象时不能使用extendsextends仅用于类定义,并定义哪个其他类是我们新类的“父”。

答案 3 :(得分: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'

?>

答案 4 :(得分:0)

你可以使用类型转换。如果a扩展b那么你可以做

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

这不完全相同,但相似。

答案 5 :(得分:0)

是的,正如科里提到的,此功能以前是requested。但在此之前,您可以创建一个变通方法。这是我的旧学校技巧

创建两个单独的类:

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();

享受:)

答案 6 :(得分:0)

您可以查看:https://github.com/ptrofimov/jslikeobject

作者实现了类似JS的对象并支持继承。

但也许使用这些对象而不是通常的对象并不是那么好。