PHP OOP:在包含的子函数中使用$ this

时间:2013-04-11 09:01:56

标签: php oop

我有一个案例在类函数中的include函数中使用$ this context。 用文字解释这有点复杂,所以我在这里给出src代码。

类文件:agents_class.php

require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."../../common/apstract_service.php");
class class_proforma extends service
{
    function __construct(){
        parent::__construct();
    }
    function getForm($params=false, $do=1){
        if($params){
            include("path/to/custom_func.php");
            return call_user_func_array("custom_func", func_get_args());
        }else{
            return include("another_func.php");
        }
    }
}

custom_func.php文件:

<?php
    function custom_func($params, $do){ //here i want to use $this; only $this 
         $this->doJop(); //calling class_proforma's/parent class method from here...
         return include("another_func.php"); //here is another file which is using $this;

    }
?>

我想在custom_func和another_func中使用$ this。 我知道传递$ this作为cusomt_func的参数可以解决这个问题。但问题是“another_func.php”是不可能改变它的$ this语法。

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

正如“mpm”和“Vlad Preda”所说,这是不可能的,所以我要用另一个类包装该函数, 从那个类我将把所有$ this调用重定向到实际的$ this上下文。

<?php
    class custom_cls{
        $service_ctx = null;
        function __construct($that){
            $this->service_ctx = $that;
        }
        function __call($function, $args) {
            return call_user_func_array(array($this->service_ctx, $function), $args);
        }
        function custom_func($params, $do){ 
             $this->doJop(); 
             return include("another_func.php"); 
        }
    }
?>

这是唯一的方法。

感谢所有回复的人。