tags:

views:

46

answers:

5
$instance = new className();
$instance['name']

How to make it work,an example?

+1  A: 

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']
Sarfraz
Not wanting to be picky again, but No, it does not depend on how you define your member variables. A class has to implement ArrayAccess in order to provide access to members through array notation or inherit from a class implementing the interface.
Gordon
@Gordon: Well, i did not know that, thanks for sharing that :)
Sarfraz
+3  A: 
$instance->name

if you want to convert object to an array you can check this.

Sinan
Not what he was asking, isnt it?
Gordon
BTW,how do you know I'm the he not the she?
@user198729 simply by being mostly ignorant about gender-neutral language. But if you want I will refer to you as *the OP* :)
Gordon
+1  A: 

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

luca
How to do it directly?
+2  A: 

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.

Yacoby
Can you illustrate the ReflectionClass solution?
+5  A: 

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);
Greg K
+1,this is what I mean.Have u tried to do it by reflectionclass?
+1 finally a good answer
Gordon