Php 通过类递归调用函数?
在我的代码中,我有两个类-第一个“Foo”启动第二个“Bar”。。。我想做的是找到一些使用父函数和变量的方法Php 通过类递归调用函数?,php,class,oop,subclass,Php,Class,Oop,Subclass,在我的代码中,我有两个类-第一个“Foo”启动第二个“Bar”。。。我想做的是找到一些使用父函数和变量的方法 class Bar { function __construct() { /* * From within this function, how do I access either the returnName() function * OR the $this -> name variable from the cl
class Bar {
function __construct() {
/*
* From within this function, how do I access either the returnName() function
* OR the $this -> name variable from the class above this?
* The result being:
*/
$this -> name = parent::returnName();
$this -> else = parent -> name;
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar();
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
我意识到“parent”的语法指的是实现或扩展,但是有可能使用这种方法吗?您可以在
Bar的构造函数中注入$this
(Foo类)
<?php
class Bar {
function __construct($fooClass) {
/*
* From within this function, how do I access either the returnName() function
* OR the $this -> name variable from the class above this?
* The result being:
*/
$this -> name = $fooClass->returnName();
$this -> else = $fooClass -> name;
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar($this);
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
小心轻放
这不是一个100%清洁的解决方案,但会起作用。您的代码应该有很好的文档记录,以避免将来的混淆
有一个非常酷的函数叫做
它为您提供有关为获取此函数而进行的所有调用的信息,包括文件名、调用的行、调用的函数、类和对象名以及参数
以下是您可以如何使用它:
class Bar {
function __construct() {
//get backtrace info
$trace = debug_backtrace();
//get the object from the function that called class
//and call the returnName() function
$this->name = $trace[1]['object']->returnName();
echo $this->name;
//want more info about backtrace? use print_r($trace);
}
}
class Foo {
function __construct() {
$this -> name = 'Fred';
$this -> var = new Bar();
}
function returnName() {
return $this -> name;
}
}
$salad = new Foo();
结果:
弗雷德
谢谢,我知道我会这么做的——尽管我不想通过辩论,除非我必须通过。以我的答案为例,看看你的班级;)对于Daan,Bar类现在尝试使用来自Foo的函数“调用未定义的方法Bar::returnName()”。解决方案?您正在静态调用returnName()
(:
)。像这样调用它$fooClass->returnName()代码>我没有使用::,我使用的是$this->returnName();我如何确保它总是使用Foo类,无论它是由Foo还是Bar调用。我问题的函数部分是目前最重要的答案,尽管这似乎对变量来说是最好的-我认为这比在调用Bar时使用$this作为参数要慢吗?你可以试试基准测试,但它运行得相当快。我在一些应用程序中使用了debug_backtrace(),整个页面的加载时间不超过0.08秒。编辑:也看看这里:谢谢!仍在研究如何让函数工作,如果需要,我一定会使用它。