请定义什么是stdClass。


当前回答

实际上,我尝试创建空的stdClass,并将速度与空类进行比较。

class emp{}

然后继续创建1000个stdClasses和emps…空类在1100微秒左右完成,而stdClasses在1700微秒以上完成。所以我想最好创建自己的虚拟类来存储数据,如果你想使用对象那么糟糕(数组写和读都快得多)。

其他回答

使用stdClass,您可以创建一个具有自己属性的新对象。 考虑以下示例,该示例将用户的详细信息表示为关联数组。

$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "smith@nomail.com";

如果需要表示与对象属性相同的细节,可以如下所示使用stdClass。

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";

如果您是Joomla开发人员,请参考Joomla文档中的这个示例以进一步了解。

实际上,我尝试创建空的stdClass,并将速度与空类进行比较。

class emp{}

然后继续创建1000个stdClasses和emps…空类在1100微秒左右完成,而stdClasses在1700微秒以上完成。所以我想最好创建自己的虚拟类来存储数据,如果你想使用对象那么糟糕(数组写和读都快得多)。

同样值得注意的是,通过使用Casting,你实际上不需要像@Bandula给出的答案那样创建一个对象。相反,您可以简单地将数组强制转换为对象并返回stdClass。例如:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

再次输出:

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

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.