phpdir

usage of __DIR__ in a class


I'm writing a very simple PHP application that returns the path of the file with a slight modification.

this is my code:

<?php
class abc {

 private $path = __DIR__ . DIRECTORY_SEPARATOR. 'moshe' . DIRECTORY_SEPARATOR;

 function doPath() {
 echo $this->path;
 }

}


$a = new abc();
$a->doPath();

I get the error:

PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';' in /mnt/storage/home/ufk/1.php on line 4

Parse error: syntax error, unexpected '.', expecting ',' or ';' in /mnt/storage/home/ufk/1.php on line 4

for some reason I cannot add connect __DIR__ using '.' to another string. what am I missing?

using PHP 5.5.13.


Solution

  • Prior to the introduction of constant scalar expressions in PHP 5.6, you could not define class properties dynamically. This example is now valid on modern PHP versions.

        private $a = 5 + 4;  // evaluated, wont work before PHP 5.6
        private $a = 9;      // works, because static value
    

    Your solution:

    class abs
    {
        private $path;
    
        public function __construct()
        {
            $this->path = __DIR__ . DIRECTORY_SEPARATOR . "moshe" . DIRECTORY_SEPARATOR;
        }
    }