不在对象上下文中时使用$ this

mhe*_*ing 5 php

也许它是在早上或我完全失明,但为什么我得到一个'致命错误:在不在对象上下文中使用$ this'在下面的代码中.那里没有任何静态.

班级:

<?php

class Property
{

    /**
     * @var string[]
     */
    private $values;

    public function __contruct($file)
    {
        $this->values = parse_ini_file($file, false);
    }

    /**
     * @return string
     */
    public function get($key, $default = null)
    {
        if (key_exists($key, $this->values)) { //<-- error
            return $this->values[$key];
        }
        return $default;
    }
}
Run Code Online (Sandbox Code Playgroud)

考试:

<?php

class PropertyTest extends Test
{

    public function testGet()
    {
        $prop = new Property($this->getResource('test.properties'));
        $this->assertEquals('foo', $prop->get('test.entry', 'xyz')); 
        $this->assertEquals('bar', $prop->get('test.entry2', 'xyz'));
        $this->assertEquals('xyz', $prop->get('test.entry3', 'xyz'));
        $this->assertEquals(null, $prop->get('test.entry3'));
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

指示跟踪的错误注释.在由Property-> get()方法的第一行引起的第一个$ prop-> get()上运行PropertyTest-> testGet()时发生错误.

除了发现的错字xdazz,以及Phil指出的弃用,user985935是对的.:)

为了简化,我的类加载器使用静态get和phpUnit错误误导我的调查和我提供给你的信息来找到我的问题.抱歉.

xda*_*azz 7

您的代码中存在拼写错误.

public function __contruct($file)
Run Code Online (Sandbox Code Playgroud)

应该是

public function __construct($file)
Run Code Online (Sandbox Code Playgroud)


小智 -4

“致命错误:不在对象上下文中时使用 $this”

$this 关键字指向对象内部的方法,只有你不能在对象外部使用 $this 我认为这就是导致你的问题的原因