usage of __DIR__ in a class

一曲冷凌霜 提交于 2019-12-14 00:58:16

问题


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.


回答1:


You cannot define class fields dinamycally

private $a = 5 + 4; // wont work, has to be evaluated
private $a = 9; // works,because static value

Your solution:

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



回答2:


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;
}


来源:https://stackoverflow.com/questions/24547682/usage-of-dir-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!