将当前类作为参数传递

时间:2013-01-02 20:59:21

标签: php class parameter-passing self-reference

我有一个这样的课程:

// file /models/person.php
class Person 
{
    public function create_path()
    {
         self::log();
         path_helper($this);  //a global function in other php file
    }

    public function log()
    {
         echo "trying to create a path";
    }

}

这就是Person实例化的方式:

//file /tools/Builder.php
include('/models/Person.php');
class Builder
{
    public function build()
    {
        $type = 'Person';
        $temp = new $type();
        $temp->create_path();
    } 
}

正如您在Person类中所述,我使用$this引用调用相关对象。但这不正确,因为显示错误:

  

消息:未定义的变量:此

我认为$this引用指向其他对象,或者它无法工作,因为该对象是从另一个脚本创建的。此外,我尝试使用self,因为调用方法没有问题,但作为参数我得到:

  

消息:使用未定义的常量自我假设'自我'

那么,你能引导我走向正确的方向吗?

2 个答案:

答案 0 :(得分:2)

我为自己测试了你的代码,只做了一些小改动。它似乎运作正常。

  • self::log()更改为$this->log()
  • 添加了全局函数path_helper(我不知道这是做什么)

<强> PHP

function path_helper(Person $object)
{
    var_dump($object);
}
class Person 
{
    public function create_path()
    {
         $this->log();
         path_helper($this);  //a global function in other php file
    }

    public function log()
    {
         echo "trying to create a path";
    }

}
class Builder
{
    public function build()
    {
        $type = 'Person';
        $temp = new $type();
        $temp->create_path();
    } 
}

$Build = new Builder();
$Build->build();

<强>结果

trying to create a path

object(Person)[2]

您的代码是正确的,并且您朝着正确的方向前进。

答案 1 :(得分:1)

您应该像这样调用日志方法:

$this->log();

因为使用self ::是为静态方法保留的。

另外,尝试调用path_helper函数:

path_helper(self);
希望我能帮助你。无法测试,但它应该可以工作。

相关问题