Jump to content

quick question about class variables


Traxus

Recommended Posts

I'm confused as to why assigning these variables in the class causes the page not to load...

 

var $RootFolder = '/shyid/';
var $PagePath = str_replace($this->RootFolder, '', dirname($_SERVER['PHP_SELF']));
var $PageSections = explode('/', $this->PagePath);

 

but when i set them on the page, everything works correctly?

 

$head->RootFolder = '/shyid/';
$head->PagePath = str_replace($head->RootFolder, '', dirname($_SERVER['PHP_SELF']));
$head->PageSections = explode('/', $head->PagePath);

 

Insight? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/209152-quick-question-about-class-variables/
Share on other sites

because you're using the var in php, which you don't need..  $RootFolder would suffice....

 

and even if it didnt but you absolutely wanted to declare them in the class file you could use:

 

this->RootFolder = '/shyid/';

this->PagePath = str_replace(this->RootFolder, '', dirname($_SERVER['PHP_SELF']));

this->PageSelections = explode('/', this->PagePath);

 

or something along those lines anywho... 

Declarations of class variables must be a constant expression, so set them in the constructor if you need default values.  Also, if not using PHP 4, then use public, private or protected:

 

class test {
   public $RootFolder;
   public $PagePath;
   public $PageSections;

   function __construct($RootFolder) {
       $this->RootFolder  = $RootFolder;
       $this->PagePath = str_replace($this->RootFolder, '', dirname($_SERVER['PHP_SELF']));
       $this->PageSections = explode('/', $this->PagePath);
   }
}
$test = new test('/shyid/');

Declarations of class variables must be a constant expression, so set them in the constructor if you need default values.  Also, if not using PHP 4, then use public, private or protected:

 

class test {
   public $RootFolder;
   public $PagePath;
   public $PageSections;

   function __construct($RootFolder) {
       $this->RootFolder  = $RootFolder;
       $this->PagePath = str_replace($this->RootFolder, '', dirname($_SERVER['PHP_SELF']));
       $this->PageSections = explode('/', $this->PagePath);
   }
}
$test = new test('/shyid/');

 

thanks for that, still new to classes/OOP

 

had no idea about __construct()

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.