PHP 中的 stdClass 是什么?

请定义什么是stdClass

答案

class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42
$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';
    }
}
$pageview=new PageShow($page);
    $pageview->show();

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

$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "smith@nomail.com";
$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";
$myNewObj->setNewVar = 'newVal';
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';

stdClass 不是匿名类或匿名对象

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

stdClass只是一个常规的预定义类。您可以使用instanceof运算符或函数get_class 。这里没什么特别的。当将其他值强制转换为对象时,PHP 使用此类。

在许多情况下,程序员使用stdClass ,数组是更好的选择,因为有用的功能以及该用例表示数据结构而不是实际对象的事实。

class emp{}
class Example {

  private $options;

  public function __construct(Array $setup)
  {
    // casting Array to stdClass object
    $this->options = (object) $setup;

    // access stdClass object in oop style - here transform data in OOP style using some custom method or something...
    echo $this->options->{'name'}; // ->{'key'}
    echo $this->options->surname;  // ->key
  }

}

$ob1 = new Example(["name" => "John", "surname" => "Doe"]);
$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

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