php 如何访问类对象内的数组值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7196770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access array values inside class object?
提问by JDesigns
I have a array like this in a function:
我在一个函数中有一个这样的数组:
$value = array("name"=>"test", "age"=>"00");
I made this $value as public inside the class abc.
我在类 abc 中将此 $value 设为 public。
Now in my other file, I want to access the values from this array, so I create an instance by:
现在在我的另一个文件中,我想访问这个数组中的值,所以我通过以下方式创建了一个实例:
$getValue = new <classname>;
$getValue->value..
I'm not sure how to proceed so that then I can access each element from that array.
我不确定如何继续,以便我可以访问该数组中的每个元素。
采纳答案by Rob
You mentioned that $valueis in a function, but is public. Can you post the function, or clarify whether you meant declaring or instantiating within a function?
你提到这$value是在一个函数中,但是是公开的。您能否发布该函数,或者澄清您的意思是在函数内声明还是实例化?
If you're instantiating it that's perfectly fine, and you can use the array keys to index $valuejust like any other array:
如果您正在实例化它,那完全没问题,您可以$value像使用任何其他数组一样使用数组键来索引:
$object = new classname;
$name = $object->value["name"];
$age = $object->value["age"];
// Or you can use foreach, getting both key and value
foreach ($object->value as $key => $value) {
echo $key . ": " . $value;
}
However, if you're talking about declaringpublic $valuein a function then that's a syntax error.
但是,如果您正在谈论在函数中声明public $value,那么这是一个语法错误。
Furthermore if you declare $value(within a function) withoutthe publicmodifier then its scopeis limited to that function and it cannot be public. The array will go out of scope at the end of the function and for all intents and purposes cease to exist.
此外,如果您$value在没有public修饰符的情况下声明(在函数内),则其范围仅限于该函数,而不能是public. 该数组将在函数结束时超出范围,并且出于所有意图和目的不复存在。
If this part seems confusing I recommend reading up on visibility in PHP.
如果这部分看起来令人困惑,我建议阅读PHP 中的可见性。
回答by Ashley
The same as you would normally use an array.
与通常使用数组相同。
$getValue = new yourClass();
$getValue->value['name'];
回答by Andrej Ludinovskov
Use code
使用代码
foreach($getValue->value as $key=>$value)
回答by Apollon
<?php
interface Nameable {
public function getName($i);
public function setName($a,$name);
}
class Book implements Nameable {
private $name=array();
public function getName($i) {
return $this->name[$i];
}
public function setName($i, $name) {
return $this->name[$i] = $name;
}
}
$interfaces = class_implements('Book');
if (isset($interfaces['Nameable'])) {
$bk1 = new Book;
$books = array('bk1', 'bk2', 'bk3', 'bk4', 'bk5');
for ($i = 0; $i < count($books); $i++)
$bk1->setName($i, $books[$i]);
for ($i = 0; $i < count($books); $i++)
echo '// Book implements Nameable: ' . $bk1->getName($i) . nl();
}
?>

