Monty
Monty

Reputation: 304

You can't run a function when defining an object property?

The code in question...

class MyClass
{
    public $template_default = dirname(__FILE__)."/default.tpl";
}

Why do I get the following error when I try to use the dirname() function when defining an object property?

Parse error: syntax error, unexpected '(', expecting ',' or ';' in ... blah blah blah

I guess object properties are not like PHP variables.

Upvotes: 0

Views: 47

Answers (2)

Austin
Austin

Reputation: 3328

If you are using PHP 5.6, you can do the following:

class MyClass
{
    public $template_default = __DIR__."/default.tpl";
}

PHP 5.6 allows simple scalar math and string concatenation in initialization now (docs), and __DIR__ is the same thing as dirname(__FILE__).

Otherwise, Drakes' answer is correct.

Upvotes: 1

Drakes
Drakes

Reputation: 23670

That's right. From the docs:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

Since dirname is a run-time function, it should be called in the constructor of the Object. So, set $template_default in the object constructor:

class MyClass {
    public $template_default;

    public function __construct(){
         $this->template_default = dirname(__FILE__). "/default.tpl";
    }
}

Upvotes: 4

Related Questions