我在下面的示例中声明了 2 个类。
class A{
protected $process;
public function __construct() {
......
$this->process=new B();
}
public function do_something(){
....
}
}
class B{
// content not important
// I need to call do_something from class A
}
我的问题是,如何从 B 类调用do_something()
A类的方法?是否可以?
从您的示例中, instance of 不可能B
知道它是由 class 的实例实例化和存储的A
。您需要以某种方式显式地创建该连接。
我不认为这甚至会起作用,但显然你可以在使用它的构造函数之前将实例传递A
给 to :B
A
class A {
protected $process;
public function __construct() {
$this->process = new B( $this );
}
public function do_something() {
var_dump( 'do_something' );
}
public function test() {
$this->process->test();
}
}
class B {
public function __construct( A $a ) {
$this->a = $a;
}
public function test() {
$this->a->do_something();
}
}
$a = new A();
$a->test(); // do_something
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句