我是 PHP 的 OOP 模型的新手,最近遇到了一个问题。 当对象B被抛入对象A并调用对象B的函数时,是否有可能在对象B的函数内部得到对象A?
考虑以下代码示例:
$test = new A();
class A
{
public function __construct () {
$arg = "something";
try{
throw new B($arg);
}
catch (B $e) {
$e->bar();
}
}
public function foo($arg){
//do something
}
}
class B extends Exception
{
public $arg;
public function __construct ($arg) {
$this->arg = $arg;
}
public function bar(){
// do something
// .....
// this is not correct, $this is not object A
// so how do i do this?
$this->foo($arg);
}
}
最佳答案
您可以将调用者对象传递给构造函数:
throw new B($this);
您的 B 构造函数会将其放入 $arg:
public $arg; // better call it $caller or somewhat
public function __construct ($arg) {
$this->arg = $arg;
}
然后,在 B 的方法中,您可以访问它:
public function bar(){
$this->arg->foo(""); // pass an argument, which is expected at function foo($arg){}
}
这是工作 IDEOne demo .
另外,@Sumurai8 已经实现了一个很好的 PHPFiddle demo .它扩展了您的构造函数,以便它同时传递参数和调用者。
关于PHP (OOP) - 从调用的函数中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33518066/