Hello,

How can I pass a root directory to variables? I am working between two servers (dev, and live) and would like an dynamic solution. I tried several flavors of this (below), but keep getting errors (unexpected T_VAR...).

class myClass {
var $currentDir = __DIR__;
var $my_xml_file = $currentDir."data/my.xml";
.
.
.
}

Recommended Answers

All 3 Replies

Well I'm not completely sure but I think you cannot declare variables like that in PHP. First of all I think you need to use public, protected or private instead of var. Secondly, you cannot refer to class variables without using "$this->". Also it is recommended that you set these variables in your __constructor() function. Example:

class myClass {

    private $currentDir;
    private $my_xml_file;

    // Create the class constructor
    public function __construct() {
        $this->currentDir = __DIR__;
        $this->my_xml_file = $currentDir."data/my.xml";
    }
}
class myClass 
{
    const CURRENTDIR = __DIR__;
    private $my_xml_file = CURRENTDIR . 'data/my.xml';
}

$currentDir does not exist in that scope. $this->currentDir is not available either and self::$currentDir only works if it's defined as static (I think). So use a constant, or use minitauros' solution using the constructor. Note that the use of var is deprecated.

Member Avatar for diafol

IMO it should be a constant, as the value can't be variable. Is it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.