Getting an error when trying to initialize this public class variable using dirname () outside the method

Why can't I set public member variable with function?

<? class TestClass { public $thisWorks = "something"; public $currentDir = dirname( __FILE__ ); public function TestClass() { print $this->thisWorks . "\n"; print $this->currentDir . "\n"; } } $myClass = new TestClass(); ?> 

Launch:

 Parse error: syntax error, unexpected '(', expecting ',' or ';' in /tmp/tmp.php on line 7 
+4
source share
9 answers

You cannot have expressions in variable declarations. You can use only constant values. dirname() may not appear in this position.

If you used PHP 5.3, you can use:

  public $currentDir = __DIR__ ; 

Otherwise, you will need to initialize $this->currentDir to __construct or.

+13
source

According to the PHP manual, your instance variables:

should be evaluated at compile time and should not depend on runtime information to be evaluated

Thus, you cannot use the dirname function in initializing a property. So just use the constructor to set the default value with:

 public function __construct() { $this->currentDir = dirname( __FILE__ ); } 
+4
source

You cannot call functions when specifying attributes.

Use this instead:

 <?php class TestClass{ public $currentDir = null; public function TestClass() { $this->currentDir = dirname(__FILE__); /* the rest here */ } } 
+2
source

It looks like you cannot call functions when specifying default values ​​for member variables.

+1
source

The reason is that you cannot assign instance variables using functions in a static way. This is simply not allowed in PHP.

May I suggest you do this:

 <? class Foo { public $currentDir; public function __construct() { $this->currentDir = dirname(__FILE__); } } ?> 
+1
source

You cannot call functions to declare class variables, unfortunately. However, you can assign the return value from dirname ( FILE ) to $ this-> currentDir from the constructor.

EDIT: Keep in mind: the constructor in PHP => 5 is called __construct (), not the class name.

+1
source

Instead, you can use this:

 public $currentDir = ''; public function TestClass() { $this->currentDir = dirname( __FILE__ ); ... 
+1
source

The dirname expression causes an error; you cannot declare the expression as a variable. You could do it though.

 <? class TestClass { public $thisWorks = "something"; public $currentDir; public function __construct() { $this->currentDir = dirname( __FILE__ ); } public function test() { echo $this->currentDir; } } 

Each time you create a new class, dirname will be set in the constructor. I also recommend excluding the closing php tag? > In your files. Helps to eliminate errors made by the header.

+1
source

do it in the constructor. $ this-> currentDir = dirname ( FILE );

and by the way print $ currentDir. "\ P"; use $ this when calling vars in class

0
source

All Articles