0

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?

1
  • 1
    You really should avoid calling a method property 'self'. This bad coding practice. Commented Jul 27, 2012 at 16:04

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

But final can only be used on methods to prevent them being overridden. It cannot protect properties from being written to (like in Java)
0

self is a PHP reserved word. You have to renamed your variable.

Comments

0

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.

Comments

0

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).

Comments

0

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; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.