denno020 Posted July 24, 2012 Share Posted July 24, 2012 I've been asked to create a class that does some stuff, and then returns an object with read only properties.. Now I've created the class and I've got everything working 100%, however I'm confused when they say to 'return an object with read only properties'.. This is the outline of my php file which contains the class and some extra lines calling it etc: class original(){ protected $self = array(); function __construct{ //do processing and build the array } function getAttributes(){ return $this->self; //return the protected array (for reading) } } $original = new original(); print_r($original->getAttributes()); Can someone please help me with returning an object or something? Thanks Denno Quote Link to comment https://forums.phpfreaks.com/topic/266157-class-returning-object-confusion/ Share on other sites More sharing options...
ignace Posted July 24, 2012 Share Posted July 24, 2012 PHP has no direct way of saying a property should be read-only. However you can emulate it when you use magic properties: // in case of an object: public function __set($key, $val) { return ; } // in case of an array: // implements ArrayAccess::offsetSet interface public function offsetSet($key, $val) { return ; } This avoids any property being overwritten (object or array). Quote Link to comment https://forums.phpfreaks.com/topic/266157-class-returning-object-confusion/#findComment-1363965 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.