Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中通过$instance[';name';]访问我的成员变量?_Php_Class - Fatal编程技术网

如何在PHP中通过$instance[';name';]访问我的成员变量?

如何在PHP中通过$instance[';name';]访问我的成员变量?,php,class,Php,Class,例如,如何使其工作?这取决于您如何定义成员变量,通常您可以这样访问它们,除非它们是公共的: $instance = new className(); $instance['name'] 但是,如果已将其定义为静态变量,则需要按如下方式访问它: $instance = new className(); $instance->name; class myclass { public $myarray = array(); // more stuff to fill that ar

例如,如何使其工作?

这取决于您如何定义成员变量,通常您可以这样访问它们,除非它们是公共的:

$instance = new className();
$instance['name']
但是,如果已将其定义为静态变量,则需要按如下方式访问它:

$instance = new className();
$instance->name;
class myclass
{
  public $myarray = array();

  // more stuff to fill that array
}
如果您想要得到这样的变量(如数组):

现在您可以这样访问它:

$instance = new className();
$instance->name;
class myclass
{
  public $myarray = array();

  // more stuff to fill that array
}
但仍然不是这样:


如果要将对象转换为数组,可以选中。

将对象转换为数组

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

不确定这是否是所问的确切问题……

您的对象必须实现。如果您希望仅访问公共属性(类变量),则还需要使用检查属性上的访问修饰符。

如果您的类实现,则您将能够以描述的方式引用类属性

摘自我链接的教程:

$instance->name

+1,这就是我的意思。你试过用reflectionclass来做吗?你能说明reflectionclass的解决方案吗?我不想再挑剔了,但不,这不取决于你如何定义你的成员变量。类必须实现ArrayAccess,以便通过数组表示法提供对成员的访问,或者从实现接口的类继承。这不是他所要求的,不是吗?顺便说一句,你怎么知道我是he而不是she?@user198729,仅仅是因为对性别无关的语言一无所知。但如果你愿意,我会称你为OP:)
$instance->name
$instance = new className();
$arrayinstance=(array)$instance ;
$arrayinstance['name'] is the same as $instance->name
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);