Php 从对象内部的数组中获取值
如果我这样做Php 从对象内部的数组中获取值,php,Php,如果我这样做 var_dump( $poll->vote_form() ); 类方法返回我想要的数组 array (size=3) 'id' => int 41 'name' => string 'sg' (length=2) 'options' => array (size=4) 116 => string 'dsg' (length=3) 117 => string 'dsg' (length=3)
var_dump( $poll->vote_form() );
类方法返回我想要的数组
array (size=3)
'id' => int 41
'name' => string 'sg' (length=2)
'options' =>
array (size=4)
116 => string 'dsg' (length=3)
117 => string 'dsg' (length=3)
118 => string 'dg' (length=2)
119 => string 'gd' (length=2)
但当我这么做的时候
echo$poll->vote_form['name']
我犯了一个错误
未定义的属性:poll::$vote\u表单
嗯,有什么问题吗?
这是班级调查的方法
public function vote_form()
{
...
$form = array('id' => $poll_id, 'name' => $poll_name, 'options' => $poll_options);
return $form;
}
试试这个:
echo $poll->vote_form()['name'];
试试这个
$data=$poll->vote_form();
echo $data['name'];
好笑的是,我昨天就有了那个代码,它工作得很好,但在不同的计算机上(可能是因为php版本更高?)。在这台计算机上,它抛出错误-解析错误:语法错误,意外'[',…..如果这不起作用,那么使用@Let me see的解决方案:)效果很好:)虽然我想知道为什么需要这样做hm:)您jsut调用poll cals的方法,并将其返回的任何内容存储在变量中。因此现在$data是一个数组,您现在可以将其作为普通数组访问,因为在您的代码示例中,您尝试访问类property称为$vote_form,而不是方法vote_form()。使用PHP>5.4,您也可以编写$poll->vote_form()['name'];但我个人的意见是,您应该使用Marko的解决方案,以与旧的PHP版本兼容。我理解这一点,但不知道为什么它在没有添加代码的情况下无法工作。总之,ty:)