douxiong2738 2013-01-02 20:59
浏览 40
已采纳

将当前类作为参数传递

I have a class like this:

// 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";
    }

}

This is the way how Person is instanciated:

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

As you note in Person class, I am calling the object in question with $this reference. But this is not correct because an error is showed:

Message: Undefined variable: this

I suppose that $this reference point to other object or it is unable to work because the object is created from another script. Also, I tried to use self because there was not problem calling methods with that, but as parameter I get:

Message: Use of undefined constant self - assumed 'self'

So, can you guide me to the right direction?

  • 写回答

2条回答 默认 最新

  • duanci5913 2013-01-02 21:07
    关注

    I tested your code out for myself, with a few minor changes. It appears to work properly.

    • Changed self::log() to $this->log()
    • Added global function path_helper (I have no idea what this does)

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

    Result

    trying to create a path
    
    object(Person)[2]
    

    Your code is correct and your going in the right direction.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM