Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

class

Why can't I set a public member variable using a function?

<?

class TestClass {

    public $thisWorks = "something";

    public $currentDir = dirname( __FILE__ );

    public function TestClass()
    {
        print $this->thisWorks . "\n";
        print $this->currentDir . "\n";
    }

}

$myClass = new TestClass();

?>

Running it yields:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /tmp/tmp.php on line 7
like image 506
TrinitronX Avatar asked Nov 29 '22 10:11

TrinitronX


1 Answers

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

If you were to use PHP 5.3 you could use:

  public $currentDir = __DIR__ ;

Otherwise you will have to initialize $this->currentDir in the __constructor.

like image 177
mario Avatar answered Dec 20 '22 08:12

mario