2016-03-17 111 views
2

在我的代码中,我有两个类 - 第一个“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 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(); 

我意识到“父”的语法是指一个实现或扩展,但是有可能使用这种方法吗?

回答

3

您可以在Bar

<?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(); 
+0

谢谢,我知道我会做这个 - 虽然我没有想通过作为一个论据,除非我绝对必须。 – lsrwLuke

+0

[debug_backtrace()](http://php.net/manual/en/function.debug-backtrace.php)查看我的答案,查看您的课程示例; –

+0

对于Daan,Bar类现在是试图使用来自Foo的函数,“调用未定义的方法Bar :: returnName()”。解决这个问题? – lsrwLuke

0

处理构造注入$this(Foo类)小心

这不是100%干净的解决方案,但会奏效。你的代码应该很好地记录下来,以避免将来的混淆。

有一个叫非常酷的功能debug_backtrace()

它为您提供有关就该好好给这个函数的所有调用,包括文件名,它被称为线,被调用的函数,类信息和对象名称和参数。

这里是你如何使用它:

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

结果:

弗雷德

+0

我的问题的功能部分是目前最重要的答案,虽然这似乎可能是最好的变量 - 我是否认为这将比调用Bar时使用$ this作为参数慢? – lsrwLuke

+0

你可以尝试一个基准测试,但它工作得很快。我在一些应用程序中使用debug_backtrace(),整个页面加载时间不会超过0.08秒。编辑:也请看看这里:[PHP的debug_backtrace在生产代码中获取有关调用方法的信息?](http://stackoverflow.com/a/347014/3338286) –

+0

谢谢!仍然在考虑让功能工作,如果需要,我一定会使用它。 – lsrwLuke