开发者

How to access my member variables by $instance['name'] in PHP?

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

How to make it work,an exampl开发者_运维知识库e?


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


$instance->name

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


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']


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜