Just trying to set the project root using filter_input. Could someone please explain why filter input for the protected and private vars inside the class reports a PARSE ERROR? However if used outside the class or inside a function of the class it works.
Is there a better way to do this so that it can be used globally? I find this is called a lot and would prefer to do it once.
$test = filter_input(INPUT_SERVER,'DOCUMENT_ROOT');
echo $test; //good
class FooBar{
protected $_test = filter_input(INPUT_SERVER,'DOCUMENT_ROOT'); //bad - Parse error: syntax error, unexpected '(', expecting ',' or ';'
private $_test2 = filter_input(INPUT_SERVER,'DOCUMENT_ROOT'); //bad - Parse error: syntax error, unexpected '(', expecting ',' or ';'
function __construct() {
}
public function getProducts(){
include_once
(filter_input(INPUT_SERVER,'DOCUMENT_ROOT').'/obj/user.php'); //good
}
}
You can not directly assign a function return value to a property in the class definition.
This is because the function could return different return values, and the class is only a blueprint which you must instantiate as an object to use.
For the objects that are created from your class definition you can initialize any property in the constructor:
class FooBar {
protected $var = null;
private $var2 = null;
function __construct() {
$this->var = func1();
$this->var2 = func2();
}
}
// no parse error
Despite of that, why do you use filter_input
on an internal constant? You only need to filter input from the outside, i.e. GET/POST/SESSION content (user input), input read from files, from external APIs etc. But you don't need to use that on internal constants like the DOCUMENT_ROOT
:
class FooBar {
private $_docroot = $_SERVER['DOCUMENT_ROOT'];
}
// no parse error