[go: nahoru, domu]

The stdClass class

(PHP 4, PHP 5, PHP 7, PHP 8)

Вступ

A generic empty class with dynamic properties.

Objects of this class can be instantiated with new operator or created by typecasting to object. Several PHP functions also create instances of this class, e.g. json_decode(), mysqli_fetch_object() or PDOStatement::fetchObject().

Despite not implementing __get()/__set() magic methods, this class allows dynamic properties and does not require the #[\AllowDynamicProperties] attribute.

This is not a base class as PHP does not have a concept of a universal base class. However, it is possible to create a custom class that extends from stdClass and as a result inherits the functionality of dynamic properties.

Короткий огляд класу

class stdClass {
}

This class has no methods or default properties.

Приклади

Приклад #1 Created as a result of typecasting to object

<?php
$obj
= (object) array('foo' => 'bar');
var_dump($obj);

Поданий вище приклад виведе:

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Приклад #2 Created as a result of json_decode()

<?php
$json
= '{"foo":"bar"}';
var_dump(json_decode($json));

Поданий вище приклад виведе:

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Приклад #3 Declaring dynamic properties

<?php
$obj
= new stdClass();
$obj->foo = 42;
$obj->{1} = 42;
var_dump($obj);

Поданий вище приклад виведе:

object(stdClass)#1 (2) {
  ["foo"]=>
  int(42)
  ["1"]=>
  int(42)
}
add a note

User Contributed Notes 1 note

up
9
Mats M
1 year ago
In PHP8 this has been changed

https://www.php.net/manual/en/migration80.incompatible.php

A number of warnings have been converted into Error exceptions:

Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.

So if you add properties to a $var, you first need to make it a stdClass()

$var = new stdClass();
$var->propp1 = "nice";
$var->propp2 = 1234;
To Top