通过字符串获取 PHP 类属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/804850/
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
Get PHP class property by string
提问by Daniel A. White
How do I get a property in a PHP based on a string? I'll call it magic. So what is magic?
如何根据字符串在 PHP 中获取属性?我会打电话给它magic。那么什么是magic?
$obj->Name = 'something';
$get = $obj->Name;
would be like...
会像...
magic($obj, 'Name', 'something');
$get = magic($obj, 'Name');
回答by Peter Bailey
Like this
像这样
<?php
$prop = 'Name';
echo $obj->$prop;
Or, if you have control over the class, implement the ArrayAccessinterface and just do this
或者,如果您可以控制该类,请实现ArrayAccess接口并执行此操作
echo $obj['Name'];
回答by laurent
If you want to access the property without creating an intermediate variable, use the {}notation:
如果您想在不创建中间变量的情况下访问该属性,请使用以下{}表示法:
$something = $object->{'something'};
That also allows you to build the property name in a loop for example:
这也允许您在循环中构建属性名称,例如:
for ($i = 0; $i < 5; $i++) {
$something = $object->{'something' . $i};
// ...
}
回答by matpie
What you're asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:
你问的是所谓的Variable Variables。您需要做的就是将您的字符串存储在一个变量中并像这样访问它:
$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');
$Object = new $Class();
// All of these will echo the same property
echo $Object->$Property; // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array
回答by ólafur Waage
Something like this? Haven't tested it but should work fine.
像这样的东西?尚未测试,但应该可以正常工作。
function magic($obj, $var, $value = NULL)
{
if($value == NULL)
{
return $obj->$var;
}
else
{
$obj->$var = $value;
}
}
回答by Jon Benedicto
Just store the property name in a variable, and use the variable to access the property. Like this:
只需将属性名称存储在一个变量中,并使用该变量来访问该属性。像这样:
$name = 'Name';
$obj->$name = 'something';
$get = $obj->$name;
回答by Muhammad Maulana
回答by Mark Allen
It is simple, $obj->{$obj->Name} the curly brackets will wrap the property much like a variable variable.
很简单,$obj->{$obj->Name} 大括号会像变量变量一样包裹属性。
This was a top search. But did not resolve my question, which was using $this. In the case of my circumstance using the curly bracket also helped...
这是一个热门搜索。但没有解决我的问题,即使用 $this。在我使用大括号的情况下也有帮助......
example with Code Igniter get instance
使用代码点火器获取实例的示例
in an sourced library class called something with a parent class instance
在带有父类实例的称为某物的源库类中
$this->someClass='something';
$this->someID=34;
the library class needing to source from another class also with the parents instance
需要从另一个类以及父实例获取的库类
echo $this->CI->{$this->someClass}->{$this->someID};
回答by VolkerK
Just as an addition: This way you can access properties with names that would be otherwise unusable
补充一点:这样您就可以访问名称不可用的属性
$x = new StdClass;$prop = 'a b'; $x->$prop = 1; $x->{'x y'} = 2; var_dump($x);
object(stdClass)#1 (2) {
["a b"]=>
int(1)
["x y"]=>
int(2)
}(不是您应该这样做,而是以防万一)。如果你想做更高级的东西,你应该研究一下reflection反射
回答by Jordan Whitfield
In case anyone else wants to find a deep property of unknown depth, I came up with the below without needing to loop through all known properties of all children.
如果其他人想找到未知深度的深层属性,我想出了以下内容,而无需遍历所有子项的所有已知属性。
For example, to find $Foo->Bar->baz, or $Foo->baz, or $Foo->Bar->Baz->dave, where $path is a string like 'foo/bar/baz'.
例如,要查找 $Foo->Bar->baz,或 $Foo->baz,或 $Foo->Bar->Baz->dave,其中 $path 是类似 'foo/bar/baz' 的字符串。
public function callModule($pathString, $delimiter = '/'){
//split the string into an array
$pathArray = explode($delimiter, $pathString);
//get the first and last of the array
$module = array_shift($pathArray);
$property = array_pop($pathArray);
//if the array is now empty, we can access simply without a loop
if(count($pathArray) == 0){
return $this->{$module}->{$property};
}
//we need to go deeper
//$tmp = $this->Foo
$tmp = $this->{$module};
foreach($pathArray as $deeper){
//re-assign $tmp to be the next level of the object
// $tmp = $Foo->Bar --- then $tmp = $Bar->baz
$tmp = $tmp->{$deeper};
}
//now we are at the level we need to be and can access the property
return $tmp->{$property};
}
And then call with something like:
然后调用类似的东西:
$propertyString = getXMLAttribute('string'); // '@Foo/Bar/baz'
$propertyString = substr($propertyString, 1);
$moduleCaller = new ModuleCaller();
echo $moduleCaller->callModule($propertyString);
回答by Nick Presta
Here is my attempt. It has some common 'stupidity' checks built in, making sure you don't try to set or get a member which isn't available.
这是我的尝试。它内置了一些常见的“愚蠢”检查,确保您不会尝试设置或获取不可用的成员。
You could move those 'property_exists' checks to __set and __get respectively and call them directly within magic().
您可以将那些“property_exists”检查分别移动到 __set 和 __get 并直接在 magic() 中调用它们。
<?php
class Foo {
public $Name;
public function magic($member, $value = NULL) {
if ($value != NULL) {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
$this->$member = $value;
} else {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
return $this->$member;
}
}
};
$f = new Foo();
$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";
// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";
?>


