PHP:如何创建对象变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4358336/
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
PHP: How to Create Object Variables?
提问by Adam
So for example I have this code:
所以例如我有这个代码:
class Object{
public $tedi;
public $bear;
...some other code ...
}
Now as you can see there are public variables inside this class. What I would like to do is to make these variables in a dynamic way, with a function something like:
现在你可以看到这个类中有公共变量。我想要做的是以动态方式创建这些变量,函数类似于:
private function create_object_vars(){
// The Array what contains the variables
$vars = array("tedi", "bear");
foreach($vars as $var){
// Push the variables to the Object as Public
public $this->$var;
}
}
So how should I create public variables in a dynamic way?
那么我应该如何以动态方式创建公共变量呢?
采纳答案by John Carter
Yes, you can do this.
是的,你可以这样做。
You're pretty much correct - this should do it:
你几乎是正确的 - 这应该这样做:
private function create_object_vars(){
// The Array of names of variables we want to create
$vars = array("tedi", "bear");
foreach($vars as $var){
// Push the variables to the Object as Public
$this->$var = "value to store";
}
}
Note that this makes use of variable variable naming, which can do some crazy and dangerous things!
请注意,这使用了变量变量命名,它可以做一些疯狂和危险的事情!
As per the comments, members created like this will be public - I'm sure there's a way of creating protected/private variables, but it's probably not simple (eg you could do it via the C Zend API in an extension).
根据评论,像这样创建的成员将是公开的 - 我确信有一种创建受保护/私有变量的方法,但这可能并不简单(例如,您可以通过扩展中的 C Zend API 来实现)。
回答by bfg9k
$vars = (object)array("tedi"=>"bear");
or
或者
$vars = new StdClass();
$vars->tedi = "bear";
回答by mario
As alternative, you can also derive your object from ArrayObject
. So it inherits array-behaviour and a few methods which make injecting attributes easier.
作为替代方案,您还可以从ArrayObject
. 所以它继承了数组行为和一些使注入属性更容易的方法。
class YourObject extends ArrayObject {
function __construct() {
parent::__construct(array(), ArrayObject::PROPS_AS_ARRAY);
}
function create_object_vars() {
foreach ($vars as $var) {
$this[$var] = "some value";
}
}
Attributes will then be available as $this->var
and $this["var"]
likewise, which may or not may suit the use case. The alternative method for setting attributes would be $this->offsetSet("VAR", "some value");
.
那么属性将作为$this->var
与$this["var"]
同样,这可能会或可能不适合使用的情况。设置属性的替代方法是$this->offsetSet("VAR", "some value");
.
Btw, there is nothing evil about variable variables. They're a proper language construct, as would be reusing ArrayObject.
顺便说一句,变量变量没有什么坏处。它们是一种合适的语言结构,就像重用 ArrayObject 一样。