如何在PHP中定义空对象?

时间:2021-05-03 22:27:53

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";

16 个解决方案

#1


638  

$x = new stdClass();

A comment in the manual sums 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.

stdClass是默认的PHP对象。stdClass没有属性、方法或父类。它不支持魔法方法,也不实现任何接口。

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的一个实例。只要需要一个通用对象实例,就可以使用stdClass。

#2


47  

The standard way to create an "empty" object is:

创建“空”对象的标准方法是:

$oVal = new stdClass();

But, with PHP >= 5.4, I personally prefer to use:

但是,使用PHP >= 5.4,我个人更喜欢使用:

$oVal = (object)[];

It's shorter and I personally consider it clearer because stdClass could 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().

(对象)[]相当于新的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:

但是记住,空($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";

#3


31  

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

来自changelog函数的引用是空的。

Objects with no properties are no longer considered empty.

没有属性的对象不再被认为是空的。

#4


15  

php.net said it is best:

php.net说它是最好的:

$new_empty_object = new stdClass();

#5


9  

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:

所以我总是尝试用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.

另外,使用这个synthax,你可以发现一些有趣的惊喜,但是对大多数情况都适用。

#6


7  

In addition to zombat's answer if you keep forgetting stdClass

如果你一直忘记了stdClass,那就给他一个答案。

   function object(){

        return new stdClass();

    }

Now you can do:

现在你能做的:

$str='';
$array=array();
$object=object();

#7


4  

You can use new stdClass() (which is recommended):

您可以使用新的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 null value 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 ) 

#8


3  

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

要以类似的方式访问stdClass中的数据,只需使用{$var}语法就可以使用asociative数组。

$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};

#9


3  

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()。像这样:

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。一个优点是,与stdClass相比,o更容易记住,而且更短,无论您将它作为类名、函数名还是两者都使用。即使在你的o类中没有任何代码,它仍然比笨拙的大写和命名的stdClass更容易记住(这可能会引发“性传播疾病类”的想法)。如果您确实自定义了o类,那么您可能会发现o()函数的用法,而不是构造函数的语法。它是一个正常的函数,返回一个值,它比构造函数要小。例如,函数名可以作为字符串传递给接受callable参数的函数。一个函数也支持链接。因此,您可以这样做:$result= o($internal_value)->some_operation_or_conversion_on_this_value();

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.

这是一个很好的基础“语言”的开始,以构建其他语言层,上面的层是用完整的内部DSLs编写的。这类似于lisp的开发风格,PHP支持的方式比大多数人想象的要好。我意识到这是一个问题的正切,但是这个问题涉及到我认为充分利用PHP的力量的基础。

#10


3  

If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property.

如果您想在动态属性中创建对象(如javascript),则不需要接收未定义属性的警告。

class stdClass {

public function __construct(array $arguments = array()) {
    if (!empty($arguments)) {
        foreach ($arguments as $property => $argument) {
            if(is_numeric($property)):
                $this->{$argument} = null;
            else:
                $this->{$property} = $argument;
            endif;
        }
    }
}

public function __call($method, $arguments) {
    $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
    if (isset($this->{$method}) && is_callable($this->{$method})) {
        return call_user_func_array($this->{$method}, $arguments);
    } else {
        throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
    }
}

public function __get($name){
    if(property_exists($this, $name)):
        return $this->{$name};
    else:
        return $this->{$name} = null;
    endif;
}

public function __set($name, $value) {
    $this->{$name} = $value;
}

}

$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value

$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null

#11


3  

You can try this way also.

你也可以试试这种方法。

<?php
     $obj = json_decode("{}"); 
     var_dump($obj);
?>

Output:

输出:

object(stdClass)#1 (0) { }

#12


2  

We can simply create an empty object by using this method:

我们可以用这个方法简单地创建一个空对象:

$object = new ObjectClass();

For example:

例如:

class ObjectClass
{
    // Something goes here
}

$object = new ObjectClass();

Now we have variable $object that is an ObjectClass but empty. Note if it contains function __construct(), then it might not be empty.

现在我们有了变量$对象,它是一个ObjectClass,但是是空的。注意,如果它包含函数__construct(),那么它可能不是空的。

I know it's an old question but it seems that some people forget about constructors.

我知道这是个老问题,但似乎有些人忘记了构造函数。

#13


1  

If you don't want to do this:

如果你不想这样做:

$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';

You can use one of the following:

你可以使用以下其中一个:

PHP >=5.4

PHP > = 5.4

$myObj = (object) [
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
];

PHP <5.4

PHP < 5.4

$myObj = (object) array(
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
);

#14


0  

Here an example with the iteration:

这里有一个迭代的例子:

<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";

foreach ($colors as $key => $value) : ?>
    <p style="background-color:<?= $value ?>">
        <?= $key ?> -> <?= $value ?>
    </p>
<?php endforeach; ?>

#15


0  

Use a generic object and map key value pairs to it.

使用通用对象并将键值对映射到它。

$oVal = new stdClass();
$oVal->key = $value

Or cast an array into an object

或将一个数组转换成一个对象。

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

#16


-1  

You have this bad but usefull technic:

你的技术很糟糕,但很有用:

$var = json_decode(json_encode([]), FALSE);

#1


638  

$x = new stdClass();

A comment in the manual sums 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.

stdClass是默认的PHP对象。stdClass没有属性、方法或父类。它不支持魔法方法,也不实现任何接口。

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的一个实例。只要需要一个通用对象实例,就可以使用stdClass。

#2


47  

The standard way to create an "empty" object is:

创建“空”对象的标准方法是:

$oVal = new stdClass();

But, with PHP >= 5.4, I personally prefer to use:

但是,使用PHP >= 5.4,我个人更喜欢使用:

$oVal = (object)[];

It's shorter and I personally consider it clearer because stdClass could 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().

(对象)[]相当于新的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:

但是记住,空($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";

#3


31  

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

来自changelog函数的引用是空的。

Objects with no properties are no longer considered empty.

没有属性的对象不再被认为是空的。

#4


15  

php.net said it is best:

php.net说它是最好的:

$new_empty_object = new stdClass();

#5


9  

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:

所以我总是尝试用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.

另外,使用这个synthax,你可以发现一些有趣的惊喜,但是对大多数情况都适用。

#6


7  

In addition to zombat's answer if you keep forgetting stdClass

如果你一直忘记了stdClass,那就给他一个答案。

   function object(){

        return new stdClass();

    }

Now you can do:

现在你能做的:

$str='';
$array=array();
$object=object();

#7


4  

You can use new stdClass() (which is recommended):

您可以使用新的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 null value 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 ) 

#8


3  

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

要以类似的方式访问stdClass中的数据,只需使用{$var}语法就可以使用asociative数组。

$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};

#9


3  

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()。像这样:

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。一个优点是,与stdClass相比,o更容易记住,而且更短,无论您将它作为类名、函数名还是两者都使用。即使在你的o类中没有任何代码,它仍然比笨拙的大写和命名的stdClass更容易记住(这可能会引发“性传播疾病类”的想法)。如果您确实自定义了o类,那么您可能会发现o()函数的用法,而不是构造函数的语法。它是一个正常的函数,返回一个值,它比构造函数要小。例如,函数名可以作为字符串传递给接受callable参数的函数。一个函数也支持链接。因此,您可以这样做:$result= o($internal_value)->some_operation_or_conversion_on_this_value();

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.

这是一个很好的基础“语言”的开始,以构建其他语言层,上面的层是用完整的内部DSLs编写的。这类似于lisp的开发风格,PHP支持的方式比大多数人想象的要好。我意识到这是一个问题的正切,但是这个问题涉及到我认为充分利用PHP的力量的基础。

#10


3  

If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property.

如果您想在动态属性中创建对象(如javascript),则不需要接收未定义属性的警告。

class stdClass {

public function __construct(array $arguments = array()) {
    if (!empty($arguments)) {
        foreach ($arguments as $property => $argument) {
            if(is_numeric($property)):
                $this->{$argument} = null;
            else:
                $this->{$property} = $argument;
            endif;
        }
    }
}

public function __call($method, $arguments) {
    $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
    if (isset($this->{$method}) && is_callable($this->{$method})) {
        return call_user_func_array($this->{$method}, $arguments);
    } else {
        throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
    }
}

public function __get($name){
    if(property_exists($this, $name)):
        return $this->{$name};
    else:
        return $this->{$name} = null;
    endif;
}

public function __set($name, $value) {
    $this->{$name} = $value;
}

}

$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value

$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null

#11


3  

You can try this way also.

你也可以试试这种方法。

<?php
     $obj = json_decode("{}"); 
     var_dump($obj);
?>

Output:

输出:

object(stdClass)#1 (0) { }

#12


2  

We can simply create an empty object by using this method:

我们可以用这个方法简单地创建一个空对象:

$object = new ObjectClass();

For example:

例如:

class ObjectClass
{
    // Something goes here
}

$object = new ObjectClass();

Now we have variable $object that is an ObjectClass but empty. Note if it contains function __construct(), then it might not be empty.

现在我们有了变量$对象,它是一个ObjectClass,但是是空的。注意,如果它包含函数__construct(),那么它可能不是空的。

I know it's an old question but it seems that some people forget about constructors.

我知道这是个老问题,但似乎有些人忘记了构造函数。

#13


1  

If you don't want to do this:

如果你不想这样做:

$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';

You can use one of the following:

你可以使用以下其中一个:

PHP >=5.4

PHP > = 5.4

$myObj = (object) [
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
];

PHP <5.4

PHP < 5.4

$myObj = (object) array(
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
);

#14


0  

Here an example with the iteration:

这里有一个迭代的例子:

<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";

foreach ($colors as $key => $value) : ?>
    <p style="background-color:<?= $value ?>">
        <?= $key ?> -> <?= $value ?>
    </p>
<?php endforeach; ?>

#15


0  

Use a generic object and map key value pairs to it.

使用通用对象并将键值对映射到它。

$oVal = new stdClass();
$oVal->key = $value

Or cast an array into an object

或将一个数组转换成一个对象。

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

#16


-1  

You have this bad but usefull technic:

你的技术很糟糕,但很有用:

$var = json_decode(json_encode([]), FALSE);