Jump to content

The right place to declare class properties


Go to solution Solved by cyberRobot,

Recommended Posts

Hi Guys

 

I was trying to set a class property today in the same way I have for a long time but it didn't work and it made me wonder whether I have been doing something wrong for a while.

 

When i try to set a session variable to a property of the class, as in $sessID below, i get a php error: "unexpected t_variable".  I have been staring at the screen for some hours but I cant actually see anything wrong with the line.

 

If I comment out the  sessID line and instead set this property  in the construct this works fine.  So few questions spring to mind:

 

1) is there some reason you can't set a variable outside of the construct like this?

2) is it best practice to set such variables as part of the construct?

3) Why do all the other variables work fine but not the session one?

 

It may yet transpire the answer to one of these questions is the answer to all :)

 

Thanks,

 

Drongo

class user_admin extends login {
	
		public $errors = array();
		private $userData = array();
		private $changePassword = false;
                public $sessID = $_SESSION['user_logged'];
		

		public function __construct(){
		
			//$this->sessID = $_SESSION['user_logged'];
				
			$this->getUserData();
			include('/forms/user-admin.php');
		
		}
}
  • Solution

From the manual (http://php.net/manual/en/language.oop5.properties.php):

 

 

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

 

 

Sorry I completely missed that when I was reading over php.net - and now it all makes perfect sense!

 

Thank you :)

Edited by Drongo_III
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.