请定义什么是stdClass。


当前回答

同样值得注意的是,还可以使用json_decode()创建stdClass对象。

其他回答

stdClass是另一个很棒的PHP特性。 您可以创建一个匿名PHP类。 让我们来看一个例子。

$page=new stdClass();
$page->name='Home';
$page->status=1;

现在假设您有另一个类,它将初始化一个页面对象并基于它执行。

<?php
class PageShow {

    public $currentpage;

    public function __construct($pageobj)
    {
        $this->currentpage = $pageobj;
    }

    public function show()
    {
        echo $this->currentpage->name;
        $state = ($this->currentpage->status == 1) ? 'Active' : 'Inactive';
        echo 'This is ' . $state . ' page';
    }
}

现在您必须使用Page object创建一个新的PageShow对象。

这里不需要写一个新的类模板,你可以简单地使用stdClass创建一个动态的类。

    $pageview=new PageShow($page);
    $pageview->show();

stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:

class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'

我不相信PHP中有基对象的概念

stdClass不是匿名类或匿名对象

这里的答案包括stdClass是匿名类甚至匿名对象的表达式。这不是真的。

stdClass只是一个常规的预定义类。你可以使用instanceof操作符或函数get_class来检查。这里没什么特别的。PHP在将其他值强制转换为对象时使用这个类。

在程序员使用stdClass的许多情况下,数组是更好的选择,因为它有有用的函数,而且这个用例表示的是数据结构,而不是真正的对象。

php.net手册有一些可靠的解释和例子,用户贡献的stdClass是什么,我特别喜欢这个http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773。

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 is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect. You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

你也可以使用object将数组强制转换为你选择的对象:

Class Example
{
   public $name;
   public $age;
}

现在要创建一个Example类型的对象并初始化它,你可以做以下任何一件事:

$example = new Example();
$example->name = "some name";
$example->age = 22;

OR

$example = new Example();
$example = (object) ['name' => "some name", 'age' => 22];

第二种方法主要用于初始化具有许多属性的对象。