对于一个新数组,我这样做:

$aVal = array();

$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";

对象是否有类似的语法

(object)$oVal = "";

$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";

$x = new stdClass();

手册中的一条评论总结得最好:

stdClass是默认的PHP对象。 stdClass没有属性,方法或 的父母。它不支持魔法 方法,并且没有实现接口。 将标量或数组强制转换为 对象的实例 stdClass。你可以使用stdClass 当你需要一个通用对象时 实例。


Php.net说它是最好的:

$new_empty_object = new stdClass();

我想指出的是,在PHP中,没有像空对象这样的东西:

$obj = new stdClass();
var_dump(empty($obj)); // bool(false)

当然$obj是空的。

另一方面,空数组在两种情况下都是空的

$arr = array();
var_dump(empty($arr));

引用changelog函数为空

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


你有这个不好但有用的技术:

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

As others have pointed out, you can use 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:

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();

这是基础“语言”构建其他语言层的一个很好的开始,顶层是用完整的内部dsl编写的。这类似于lisp开发风格,PHP对它的支持比大多数人想象的要好得多。我意识到这个问题有点离题,但这个问题涉及到我认为的充分利用PHP功能的基础。

EDIT/UPDATE: I no longer recommend any of this. It makes it hard for static analysis tools and IDEs and custom AST based tools to understand, validate, help you lookup or write your code. Generally magic is bad except in some cases if you are able to get your tools to understand the magic and if it you do it in a standard enough way that even standard community tools will understand it or if your tools are so advanced and full featured that you only use your own tools. Also, I think they are deprecating the ability to add properties to random objects in an upcoming version of PHP, I think it will only work with certain ones, but I don't recommend using that feature anyways.


除了僵尸的答案,如果你一直忘记stdClass

   function object(){

        return new stdClass();

    }

现在你可以做:

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

以类似的方式访问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};

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

$oVal = new stdClass();

但我个人更喜欢用:

$oVal = (object)[];

它更短,我个人认为它更清楚,因为stdClass可能会误导新手程序员(例如。“嘿,我想要一个对象,不是一个类!”…)


(object)[]等价于new stdClass()。

请参阅PHP手册(此处):

stdClass:通过类型转换到对象创建。

在这里:

如果将对象转换为对象,则不修改该对象。如果将任何其他类型的值转换为对象,则会创建stdClass内置类的一个新实例。

这里(从PHP 7.3.0开始,var_export()导出一个使用(object)转换数组的对象):

现在将stdClass对象作为数组导出到对象((对象)数组(…)),而不是使用不存在的方法stdClass::__setState()。实际效果是现在stdClass是可导出的,生成的代码甚至可以在早期版本的PHP上工作。


但是请记住empty($oVal)返回false,正如@PaulP所说:

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

关于你的例子,如果你写:

$oVal = new stdClass();
$oVal->key1->var1 = "something"; // this creates a warning with PHP < 8
                                 // and a fatal error with PHP >=8
$oVal->key1->var2 = "something else";

PHP < 8创建以下Warning,隐式创建属性key1(对象本身)

警告:从空值创建默认对象

PHP >= 8创建以下错误:

错误:未定义的常量“key1”

在我看来,你最好的选择是:

$oVal = (object)[
  'key1' => (object)[
    'var1' => "something",
    'var2' => "something else",
  ],
];

如果你想创建一个具有动态属性的对象(如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

你可以使用new stdClass()(这是推荐的):

$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);

// outputs:
// stdClass Object ( [name] => John ) 

或者你可以将一个空数组转换为一个对象,该对象会生成stdClass内置类的一个新的空实例:

$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);

// outputs: 
// stdClass Object ( [name] => John )  

或者你可以将空值转换为一个对象,该对象会生成stdClass内置类的一个新的空实例:

$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);

// outputs:
// stdClass Object ( [name] => John ) 

简短的回答

$myObj = new stdClass();

// OR 

$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

长回答

我喜欢在JavaScript中创建匿名类型的对象是多么容易:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value

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

但由于这基本上是一个数组,你不能像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)"

好吧,你可以这样做,但在我看来并不实用/干净:

$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar

此外,使用这个语法您可以发现一些有趣的惊喜,但在大多数情况下都可以正常工作。


你也可以试试这种方法。

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

输出:

object(stdClass)#1 (0) { }

如果你不想这样做:

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

您可以使用以下其中之一:

PHP > = 5.4

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

PHP < 5.4

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

这里有一个迭代的例子:

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

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

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

或者将数组强制转换为对象

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

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

当您将标量或数组强制转换为Object时,您将获得stdClass的实例。只要需要泛型对象实例,就可以使用stdClass。

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass不是基类!PHP类不会自动继承任何类。所有的类都是独立的,除非它们显式地扩展另一个类。PHP在这方面不同于许多面向对象的语言。

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

你不能在你的代码中定义一个名为stdClass的类。该名称已被系统使用。你可以定义一个名为“Object”的类。

您可以定义一个扩展stdClass的类,但是您不会得到任何好处,因为stdClass什么也不做。

(在PHP 5.2.8上测试)


你也可以通过解析JSON得到一个空对象:

$blankObject= json_decode('{}');