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.
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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With