snivek Posted January 6, 2007 Share Posted January 6, 2007 Can you access class properties directly by calling the property name or do you have to create a method to return it?[code]<?phpClass Veggy { var $color; Function Veggy($color) { $this->$color = $color } Function get_color(){ return $this->$color; }}$spinach = new Veggy("green")print $spinach->$color; /* will that work? */print $spinach->get_color(); /*this shoulwork */?>[/code] Link to comment https://forums.phpfreaks.com/topic/33048-class-properties/ Share on other sites More sharing options...
utexas_pjm Posted January 6, 2007 Share Posted January 6, 2007 In PHP4 all member data are public, that is, they can be viewed and mutated directly. In PHP 5 you can make member data public, private, or protected. Private and proteected member data can only be viewed and mutated via public methods (when not within the context of the class or a subclass).PHP4 - these will both work.[code]<?phpClass Veggy { var $color; Function Veggy($color) { $this->$color = $color } Function get_color(){ return $this->$color; }}$spinach = new Veggy("green")print $spinach->$color; /* will that work? */print $spinach->get_color(); /*this shoulwork */?>[/code]PHP5 - only the latter will work as expected[code]<?phpClass Veggy { protected $color; public function __construct($color) { $this->$color = $color } public function get_color(){ return $this->$color; }}$spinach = new Veggy("green")print $spinach->$color; /* will that work? No*/print $spinach->get_color(); /*this shoulwork, and it does. */?>[/code]Best,Patrick Link to comment https://forums.phpfreaks.com/topic/33048-class-properties/#findComment-153982 Share on other sites More sharing options...
snivek Posted January 6, 2007 Author Share Posted January 6, 2007 Does the following work if the variable is marked Public?[code]<?phpClass Veggy { public $color; #marked public public function __construct($color) { $this->$color = $color } public function get_color(){ return $this->$color; }}$spinach = new Veggy("green")print $spinach->$color; /* DOES THIS WORK NOW? If not, what is the point in a PUBLIC var if I still have to use a public method to read/write it?*/?>[/code] Link to comment https://forums.phpfreaks.com/topic/33048-class-properties/#findComment-153986 Share on other sites More sharing options...
emehrkay Posted January 6, 2007 Share Posted January 6, 2007 i thought it would be$spinach->color;yes it would work as a public var Link to comment https://forums.phpfreaks.com/topic/33048-class-properties/#findComment-153988 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.