$instance = new className();
$instance['name']
How to make it work,an example?
$instance = new className();
$instance['name']
How to make it work,an example?
It depends on how you have defined your member variables, normally you can access them like this unless they are public:
$instance = new className();
$instance->name;
If however you have defined it as static variable, you need to access it like this:
$instance = new className();
$instance::$name;
If you meant to get variables like this (like array):
$instance = new className();
$instance['name'] // <----------- won't be like that exactly
You need to define an array in your class:
class myclass
{
public $myarray = array();
// more stuff to fill that array
}
Now you can access it like this:
$instance = new className();
$instance->myarray['name'];
But not like this still:
$instance = new className();
$instance['name']
cast the object as array
$instance = new className();
$arrayinstance=(array)$instance ;
$arrayinstance['name'] is the same as $instance->name
not sure if it was the exact question asked....
Your object must implement ArrayAccess. If you want to be able to access only the public properties (class variables) you will need to also use the ReflectionClass to check the access modifiers on the property.
If your class implements PHP's SPL ArrayAccess then you will be able to reference class attributes in the manner you describe.
Taken from the tutorial I linked:
class book implements ArrayAccess {
public $title;
public $author;
public $isbn;
public function offsetExists($offset) {
return isset($this->$offset);
}
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
public function offsetGet($offset) {
return $this->$offset;
}
public function offsetUnset($offset) {
unset($this->$offset);
}
}
/*** a new class instance ***/
$book = new book;
/*** set some book properties ***/
$book['title']= 'Pro PHP';
$book['author'] = 'Kevin McArthur';
$book['isbn'] = 1590598199;
print_r($book);