What is stdClass in PHP?

2018-12-31 03:46发布

Please define what stdClass is.

标签: php stdclass
16条回答
路过你的时光
2楼-- · 2018-12-31 04:11

stdClass objects in use

The stdClass allows you to create anonymous classes and with object casting you can also access keys of an associative array in OOP style. Just like you would access the regular object property.

Example

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

will echo

John Doe

查看更多
人间绝色
3楼-- · 2018-12-31 04:12

You can also use object to cast arrays to an object of your choice:

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

Now to create an object of type Example and to initialize it you can do either of these:

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

OR

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

The second method is mostly useful for initializing objects with many properties.

查看更多
妖精总统
4楼-- · 2018-12-31 04:19

stdClass is a another great PHP feature. You can create a anonymous PHP class. Lets check an example.

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

now think you have a another class that will initialize with a page object and execute base on it.

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

Now you have to create a new PageShow object with a Page Object.

Here no need to write a new Class Template for this you can simply use stdClass to create a Class on the fly.

    $pageview=new PageShow($page);
    $pageview->show();
查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 04:25

Using stdClass you can create a new object with it's own properties. Consider the following example that represents the details of a user as an associative array.

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

If you need to represent the same details as the properties of an object, you can use stdClass as below.

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

If you are a Joomla developer refer this example in the Joomla docs for further understanding.

查看更多
登录 后发表回答