Reputation: 3309
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 Book(){
protected $self = array();
function __construct{
//do processing and build the array
}
function getAttributes(){
return $this->self; //return the protected array (for reading)
}
}
$book = new Book();
print_r($book->getAttributes());
How can I return an object or something?
Upvotes: 0
Views: 63
Reputation: 5166
read only property means you can access them but can not write them
class PropertyInaccessible {
//put your code here
protected $_data = array();
public function __get($name) {
if(isset ($this->_data[$name]))
return $this->_data[$name];
}
public function __set($name, $value) {
throw new Exception('Can not set property directly');
}
public function set($name, $value) {
$this->_data[$name] = $value;
}
}
Upvotes: 0
Reputation: 71384
Something like:
Class Book {
protected $attribute;
protected $another_attribute;
public function get_attribute(){
return $this->attribute;
}
public function get_another_attribute() {
return $this->another_attribute;
}
public method get_this_book() {
return $this;
}
}
Now this is kind of s silly example because Book->get_this_book() would return itself. But this should give you an idea of how to set of getters on protected properties such that they are read only. And how to reutrn an object (in this case it returns itself).
Upvotes: 0
Reputation: 14237
You are probably looking for the keyword final
. Final means the object/method cannot be overridden.
Protected means that the object/method can only be accessed by the class who it belongs to.
Since self
is a reserved keyword, you need to change that as well as your declarations. Rename $self
an $this->self
to $data
and $this->data
Upvotes: 1
Reputation: 7040
What they're referring to is an object with private
or protected
properties which can only be accessed by setters
/getters
. The property will be read-only if you only define the getter
method.
Upvotes: 0