问题
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