Jump to content

properties in php classes


skaterdav85

Recommended Posts

I created a test php class, but i'm getting an error. Obviously my property was set up wrong but I need to set it up in an array format since I am using the CodeIgniter framework. Anyone know what is wrong with my property?

class Test {	public $_DATA['title'] = "Contact";	}

My error says:Parse error: syntax error, unexpected '[', expecting ',' or ';' in /Applications/MAMP/htdocs/TIS/test.php on line 5

Link to comment
Share on other sites

You seem to be creating the 'title' element before you create the $_DATA array. That is why the '[' is unexpected. You also seem to be declaring only the 'title' element as public, but I don't think you can specify the visibility of one element of a simple array.Is this what you're after?

class Test {   public $_DATA = array('title' => 'contact');}$ob = new Test();echo $ob->_DATA['title'];

Now the _DATA property, which is an array, is public, and so are all its elements.

Link to comment
Share on other sites

P.S. it's not really good practice to initialize variables outside of a method in a class.

Link to comment
Share on other sites

Normally I'd use a constant. The property was holding the value for the title of my page in CodeIgniter. From my knowledge of CodeIgniter so far, all my data has to be in an array when it is passed to a view, and the elements of the array are accessed by the index as regular variables in the view. Thus, the title element of the $_DATA array would be accessed like $title in the view. This is why I had to put the page title in an array, and for each method in my controller class, I did not want to initialize the title property since that seemed redundant.

Link to comment
Share on other sites

P.S. it's not really good practice to initialize variables outside of a method in a class.
If the value is always the same (regardless of construct arguments) - why?In some languages (I think C++ was among those, but I'm not sure), it's a bad practice, because those assignments are part of the default constructor, so as soon as you have any constuctor, you destroy the default constructor and therefore those initializations. In PHP, that's not a problem, because there is no default constructor in the traditional sence. There's just things that PHP always does when instantiating a class, and stuff that you may define in addition to that at the __construct() magic method.
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...