Nathan L.
Nathan L.

Reputation: 159

PHP Cannot access empty property error

I am getting the following error and I can't seem to figure out why or how it's getting triggered.

Fatal error: Cannot access empty property in /home/content/p/l/a/plai1870/html/com/php/Bone/Compiler.php on line 18

Line 18 is

throw new LogicException($this->$compilers[$language]." is not a supported compiler.");

Here is Compiler.php

<?php
namespace Bone;
use LogicException;

class Compiler implements \Bone\Interfaces\Compiler {

    protected $compiler;

    protected $compilers = array(
        "php"           => "PHP",
        "as3"           => "ActionScript3",
        "javascript"    => "Javascript"
    );

    public function __construct($language) {
        $language = strtolower($language);
        if (!isset($this->$compilers[$language])) {
            throw new LogicException($this->$compilers[$language]." is not a supported compiler.");
        }
        $compiler = "\Bone\Compilers\\".$this->$compilers[$language]."\Compiler";
        $this->compiler = new $compiler();
    }

    public function buildDefinition($object, $path = null) {
        return $this->compiler()->buildInterface($object, $path);
    }

    public function buildObject($object, $path = null) {
        return $this->compiler->buildObject($object, $path);
    }   

    public function parameters($method) {
        return;
    }

    public function save($data, $path) {
        return;
    }
}
?>

EDIT And I'm calling it with:

$compiler = new \Bone\Compiler("php");

Upvotes: 1

Views: 1766

Answers (2)

hakre
hakre

Reputation: 197991

Sorry if this is the most obvious, but:

throw new LogicException($this->$compilers[$language]." is not a supported compiler.");

As it has been checked that the property does not exists, shouldn't it be:

throw new LogicException("$language is not a supported compiler.");

?

Edit:

$this->$compilers[$language]
       ^- variable property

Remove the $ there:

$this->compilers[$language]

Then you can check if the entry in the array is set, not if a propery with the name of the value inside the (unset) array $compilers (local variable) is set.

When developing, always switch on warnings and notices (highest error level you can imagine) to not run into these problems without having PHP warn you first.

Upvotes: 7

gen_Eric
gen_Eric

Reputation: 227270

Your array is $this->compilers, not $this->$compilers.

$compilers doesn't exist in your function, so $this->$compilers was looking for a blank property.

Upvotes: 3

Related Questions