Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of __DIR__ in a class

Tags:

php

dir

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.

like image 713
ufk Avatar asked Jul 03 '14 07:07

ufk


2 Answers

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;
    }
}
like image 113
Mārtiņš Briedis Avatar answered Sep 27 '22 22:09

Mārtiņš Briedis


You can't calculate properties in their class definition.

If you need a variable to be initialized to a default value that can only be determined by an expression, you can do it with a constructor.

public function __construct ()
{
    $this -> path = __DIR__ . DIRECTORY_SEPARATOR. 'moshe' . DIRECTORY_SEPARATOR;
}

However, the above is a really bad design for various reasons that I won't get into here. You're far better off passing the path in as an argument, as this will allow you far more flexibility. For example, if you want to test the class you can have it write to a different location when testing it and not affect live data.

public function __construct ($path)
{
    if (!is_dir ($path)) {
        // Throwing an exception here will abort object creation
        throw new InvalidArgumentException ("The given path '$path' is not a valid directory");
    }

    $this -> path = $path;
}
like image 44
GordonM Avatar answered Sep 27 '22 22:09

GordonM