Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $this when not in object context

Tags:

php

maybe it is to early in the morning or I'm totally blind, but why to I get a 'Fatal error: Using $this when not in object context' in the following code. There is nothing static in there.

The class:

<?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;
    }
}

The test:

<?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'));
    }
}

Edit

The error comments indicating the trace. The error occures while running the PropertyTest->testGet() on the the first $prop->get() caused by the first line of the Property->get() method.

Solution

Beside the typo xdazz found, and the deprecation Phil pointed at, user985935 was right. :)

To make it short, my class loader used the static get and the phpUnit error mislead my investigations and my information I offer you for finding my problem. Sorry.

like image 683
mheinzerling Avatar asked Oct 23 '22 19:10

mheinzerling


1 Answers

There is a typo in your code.

public function __contruct($file)

which should be

public function __construct($file)
like image 118
xdazz Avatar answered Nov 08 '22 08:11

xdazz