如何在 PHP 中定义一个空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1434368/
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 define an empty object in PHP
提问by ed209
with a new array I do this:
用一个新数组我这样做:
$aVal = array();
$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";
Is there a similar syntax for an object
对象是否有类似的语法
(object)$oVal = "";
$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";
回答by zombat
$x = new stdClass();
A comment in the manualsums it up best:
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.
When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
stdClass 是默认的 PHP 对象。stdClass 没有属性、方法或父级。它不支持魔术方法,也没有实现任何接口。
当您将标量或数组转换为 Object 时,您将获得 stdClass 的一个实例。只要需要通用对象实例,就可以使用 stdClass。
回答by cgaldiolo
The standard way to create an "empty" object is:
创建“空”对象的标准方法是:
$oVal = new stdClass();
But, with PHP >= 5.4, I personallyprefer to use:
但是,对于 PHP >= 5.4,我个人更喜欢使用:
$oVal = (object)[];
It's shorter and I personally consider it clearer because stdClasscould be misleading to novice programmers (i.e. "Hey, I want an object, not a class!"...).
它更短,我个人认为它更清晰,因为stdClass可能会误导新手程序员(即“嘿,我想要一个对象,而不是一个类!”...)。
The same with PHP < 5.4 is:
与 PHP < 5.4 相同的是:
$oVal = (object) array();
(object)[]is equivalent to new stdClass().
(object)[]相当于new stdClass()。
See the PHP manual (here):
请参阅 PHP 手册(此处):
stdClass: Created by typecasting to object.
stdClass:通过对对象进行类型转换而创建。
and (here):
和(这里):
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
如果将对象转换为对象,则不会对其进行修改。如果将任何其他类型的值转换为对象,则会创建 stdClass 内置类的新实例。
However remember that empty($oVal) returns false, as @PaulP said:
但是请记住,empty($oVal) 返回 false,正如@PaulP 所说:
Objects with no properties are no longer considered empty.
没有属性的对象不再被认为是空的。
Regarding your example, if you write:
关于你的例子,如果你写:
$oVal = new stdClass();
$oVal->key1->var1 = "something"; // PHP creates a Warning here
$oVal->key1->var2 = "something else";
PHP creates the following Warning, implicitly creating the property key1(an object itself)
PHP 创建以下警告,隐式创建属性key1(对象本身)
Warning: Creating default object from empty value
警告:从空值创建默认对象
This could be a problem if your configuration (see error reporting level) shows this warning to the browser. This is another entire topic, but a quick and dirty approach could be using the error control operator (@)to ignore the warning:
如果您的配置(请参阅错误报告级别)向浏览器显示此警告,则这可能是一个问题。这是另一个完整的主题,但一种快速而肮脏的方法可能是使用错误控制运算符 (@)来忽略警告:
$oVal = new stdClass();
@$oVal->key1->var1 = "something"; // the warning is ignored thanks to @
$oVal->key1->var2 = "something else";
回答by PaulP
I want to point out that in PHP there is no such thing like empty object in sense:
我想指出,在 PHP 中没有像空对象这样的东西:
$obj = new stdClass();
var_dump(empty($obj)); // bool(false)
but of course $obj will be empty.
但当然 $obj 将是空的。
On other hand empty array mean empty in both cases
另一方面,空数组在两种情况下都意味着空
$arr = array();
var_dump(empty($arr));
Quote from changelog function empty
来自变更日志功能的引用为空
Objects with no properties are no longer considered empty.
没有属性的对象不再被认为是空的。
回答by HungryCoder
php.net said it is best:
php.net 说最好:
$new_empty_object = new stdClass();
回答by campsjos
I love how easy is to create objects of anonymous type in JavaScript:
我喜欢在 JavaScript 中创建匿名类型的对象是多么容易:
//JavaScript
var myObj = {
foo: "Foo value",
bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value
So I always try to write this kind of objects in PHP like javascript does:
所以我总是尝试像 javascript 那样用 PHP 编写这种对象:
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => "Bar value"
];
//PHP < 5.4
$myObj = (object) array(
"foo" => "Foo value",
"bar" => "Bar value"
);
echo $myObj->foo; //Output: Foo value
But as this is basically an array you can't do things like assign anonymous functions to a property like js does:
但由于这基本上是一个数组,因此您不能像 js 那样将匿名函数分配给属性:
//JavaScript
var myObj = {
foo: "Foo value",
bar: function(greeting) {
return greeting + " bar";
}
};
console.log(myObj.bar("Hello")); //Output: Hello bar
//PHP >= 5.4
$myObj = (object) [
"foo" => "Foo value",
"bar" => function($greeting) {
return $greeting . " bar";
}
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"
Well, you can do it, but IMO isn't practical / clean:
好吧,你可以做到,但 IMO 不实用/干净:
$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar
Also, using this synthax you can find some funny surprises, but works fine for most cases.
此外,使用这个合成器你会发现一些有趣的惊喜,但在大多数情况下都可以正常工作。
回答by RafaSashi
In addition to zombat's answer if you keep forgetting stdClass
如果你一直忘记的话,除了 zombat 的回答 stdClass
function object(){
return new stdClass();
}
Now you can do:
现在你可以这样做:
$str='';
$array=array();
$object=object();
回答by Amr
You can use new stdClass()(which is recommended):
您可以使用new stdClass()(推荐):
$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
或者,您可以将空数组转换为生成 stdClass 内置类的新空实例的对象:
$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert the nullvalue to an object which produces a new empty instance of the stdClass built-in class:
或者您可以将null值转换为一个对象,该对象生成 stdClass 内置类的新空实例:
$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);
// outputs:
// stdClass Object ( [name] => John )
回答by GCoro
to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.
要以与关联数组类似的方式访问 stdClass 中的数据,只需使用 {$var} 语法。
$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";
// then to acces it directly
echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};
// or what you may want
echo $myObj->{$myStringVar};
回答by still_dreaming_1
As others have pointed out, you can use stdClass. However I think it is cleaner without the (), like so:
正如其他人指出的那样,您可以使用 stdClass。但是我认为没有 () 会更干净,如下所示:
$obj = new stdClass;
However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don't need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:
但是,根据这个问题,您似乎真正想要的是能够动态地向对象添加属性。尽管可以,但您不需要为此使用 stdClass。你真的可以使用任何类。只需创建任何类的对象实例并开始设置属性。我喜欢创建我自己的类,它的名字只是 o,具有一些我喜欢在这些情况下使用的基本扩展功能,并且非常适合从其他类扩展。基本上它是我自己的基础对象类。我也喜欢有一个简单命名为 o() 的函数。像这样:
class o {
// some custom shared magic, constructor, properties, or methods here
}
function o() {
return new o;
}
If you don't like to have your own base object type, you can simply have o() return a new stdClass. One advantage is that o is easier to remember than stdClass and is shorter, regardless of if you use it as a class name, function name, or both. Even if you don't have any code inside your o class, it is still easier to memorize than the awkwardly capitalized and named stdClass (which may invoke the idea of a 'sexually transmitted disease class'). If you do customize the o class, you might find a use for the o() function instead of the constructor syntax. It is a normal function that returns a value, which is less limited than a constructor. For example, a function name can be passed as a string to a function that accepts a callable parameter. A function also supports chaining. So you can do something like: $result= o($internal_value)->some_operation_or_conversion_on_this_value();
如果您不喜欢拥有自己的基本对象类型,您可以简单地让 o() 返回一个新的 stdClass。一个优点是 o 比 stdClass 更容易记住并且更短,无论您将它用作类名、函数名还是两者。即使您的 o 类中没有任何代码,它仍然比笨拙的大写和命名的 stdClass(这可能会引发“性传播疾病类”的想法)更容易记住。如果您确实自定义了 o 类,您可能会发现使用 o() 函数而不是构造函数语法。它是一个返回值的普通函数,其限制比构造函数少。例如,函数名称可以作为字符串传递给接受可调用参数的函数。一个函数也支持链接。因此,您可以执行以下操作:
This is a great start for a base "language" to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.
对于基础“语言”来说,这是一个很好的开始,可以在其上构建其他语言层,顶层是用完整的内部 DSL 编写的。这类似于 lisp 的开发风格,PHP 对它的支持比大多数人意识到的要好。我意识到这对这个问题有点切题,但这个问题涉及我认为充分利用 PHP 功能的基础。
回答by Mukesh Jeengar
You can try this way also.
你也可以试试这个方法。
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
Output:
输出:
object(stdClass)#1 (0) { }

