PHP如何引用类方法定义?

时间:2019-06-15 01:47:15

标签: php

我想将一个函数(一个类的方法)绑定到另一个类。我如何实现这一目标的任何想法? 这是我想要的示例:

class A {
  protected $prop = "prop A";

  function method($arg1, ...) {
    return $this->prop;
  }    
}

class B {
  protected $prop = "prop B";

  // need help here
}

所以我想将“ A”类的“方法”“绑定”到“ B”类,这样就可以进行$b = new B(); $b->method($arg1, ...);并获得"prop B";

提前谢谢!

我尝试过:

class B {
  protected $instance;
  protected $prop = "prop B";

  public function __construct($instance) {
    $this->instance = $instance;
  }

  public function __call($method, $args) {
    return call_user_func_array([$this->instance, $method], $args);
  }
}

$b = new B(new A());
$b->method();

但仍输出“ prop A”; 我也尝试过:

class B {
  protected $prop = "prop B";

  public function __call($method, $args) {
    return call_user_func_array(Closure::bind($this->$method, $this, get_called_class()), $arguments);
  }
}

$a = new A();
$b = new B();
$b->method = $a->method;
$b->method();

但是我收到此错误:Closure::bind() expects parameter 1 to be Closure, null given...。 最后我也尝试过这个:

class B {
  protected $instance;
  protected $prop = "prop B";

  public function __construct($instance) {
    $this->instance = $instance;
  }

  public function __call($method, $args) {
    $new_method = $this->instance->$method->bindTo($this);

    return call_user_func_array($new_method, $args);
  }
}

$b = new B(new A());
$b->method();

在这里,错误提示$this->instance->$methodnull

1 个答案:

答案 0 :(得分:0)

使用依赖注入,您可以访问传递的对象:

class A {
  public function speak() { return ‘meow’; }
}

class B {
  public function __construct($obj) {
    $this->a = $obj;
  }
}

$demo = new B( new A));
print $demo->a->speak();
// => meow

从这里开始,如果您想让B->说话指的是A->说话:

class A {
  public function speak() { return ‘meow’; }
}

class B {
  public function __construct($obj) {
    $this->a = $obj;
  }

  public function speak() {
    return $this->a->speak();
  }
}

$demo = new B( new A));
print $demo->a->speak(); // meow
print $demo->speak(); // meow

或者,如果B是A的一种特殊类型:

// use obj A above

class B extends A {
  // do stuff B knows
}

$demo = new B;
print $demo->speak();
// => meow

如果您想在两个类中使用完全相同的方法,那么也许您想要的是特征。特性或多或少是对象的一个​​包含,它使对象“共享”代码。 (我个人认为这是违反DRY的一种不错的方式,可以通过DI更好地进行处理...但是比我在语言中包含的人更聪明的人)

使用特征就是这样(仔细检查文档,我从未使用过)

trait sharedMethod {
  public function speak() {
    return $this->prop;
  }
}

class A {
  use sharedMethod;
  public $prop = “I’m from A”;
}

class B {
  use sharedMethod;

  public $prop = “I’m from B”;

  public function __construct(object $a) {
    $this->a = $a;
  }

  /**
   * use this to get A’s method, or omit to keep B’s method 
   */
  public function speak() {
    return $this->a->speak();
  }
}

$demo = new B( new A));
print $demo->speak(); // I’m from A


// if you don’t override the method

$demo = new B( new A));
print $demo->speak(); // I’m from B