Fluf Posted June 2, 2009 Share Posted June 2, 2009 Question is, why can't i use $config['conf'] variable in class? It gives me following error Parse error: syntax error, unexpected '[', expecting ',' or ';' in /usr/local/apache/htdocs/class/file.php on line 4 It works if i don't put it in class, but i need it in there.. <?php class test { public $config['conf'] = "server"; function man() { $this->config['conf'] = "localhost"; return $this->config['conf']; } } $new = new test(); echo $new->man(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/160681-variable-in-classes/ Share on other sites More sharing options...
anupamsaha Posted June 2, 2009 Share Posted June 2, 2009 Try this. <?php class test { public $config = array(); public function __construct() { $this->config['conf'] = 'server'; } function man() { $this->config['conf'] = "localhost"; return $this->config['conf']; } } $new = new test(); echo $new->man(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/160681-variable-in-classes/#findComment-847986 Share on other sites More sharing options...
keeps21 Posted June 2, 2009 Share Posted June 2, 2009 or try this - you get the same outcome as intended in your post and the post above - why are you setting the $config['conf'] to server in the first place? I believe you can't assign a value to a variable while declaring it as a class variable - though i'm sure I'll be corrected if I'm wrong. Which is why it's working outside of a class but not inside. <?php class test { public $config; function man() { $this->config['conf'] = "localhost"; return $this->config['conf']; } } $new = new test(); echo $new->man(); Quote Link to comment https://forums.phpfreaks.com/topic/160681-variable-in-classes/#findComment-847994 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.