Php is standard class

Stdclass

Stdclass is a Standard Defined Classes. Stdclass is a generic empty class created by PHP. PHP uses this class when casting.

It is just a predefined class like Object in Java. It’s not the base class of the objects.

Scroll for More Useful Information and Relevant FAQs

Is stdClass the base class of the objects?

StdClass is NOT the Base class of the object. Let’s see with below example

class abc <> $object = new abc(); if ($object instanceof stdClass) < echo 'Yes! It is'; >else < echo 'No, StdClass is NOT Base class of the object'; >//Output: 'No, StdClass is NOT Base class of the object

Why does it throw an PHP Fatal error ‘cannot use an object of type stdclass as array’ and How to fix this error?

Why did it happen? Answer is in Question too that our code is trying to access values as array even though it was object type.

Читайте также:  Python multiindex drop level

Solution: Just change of accessing value from generic bracket like
$array[‘name_of_param’] To $array->name_of_param .

Let’s understand through example:

Throw Error:

// Throw Error: $array = array( 'name' => 'demo', 'age' => '21', 'address' => '123, wall street' ); $object = (object) $array; echo $object instanceof stdClass ? "Yes" : "No"; // Output : Yes //Trying to access as array echo $object['name']; // Throws : PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array .
$array = array( 'name' => 'demo', 'age' => '21', 'address' => '123, wall street' ); $object = (object) $array; echo $object instanceof stdClass ? "Yes" : "No"; // Output : Yes echo $object->name; //Output: demo

Ways to Convert stdclass object to an associative array in php?

We can convert into array from stdclass in following ways:

Convert stdclass to associative array using json_decode

name = "Demo"; $stdObj->age = 20; $array = json_decode(json_encode($stdObj), true); // Json decode with second argumen true will return associative arrays. print_r($array); //Output Array ( [name] => Demo [age] => 20 )

Typecasting

Simple objects can convert using (array) typecasting.

Example: $array = (array) $stdObj;

Complex objects or lists of objects are converted into a multidimensional array by looping through each single object with typecasting.

How to fix stdclass undefined property error?

stdclass undefined property error reported when we try to access property which does not exist/declared. It’s best practise to check whether a property is set or not. We can use the php inbuilt function isset() for such cases.

Let see with below example

Why stdclass undefined property issue? Let’s see with this example

$stdObj = new stdClass(); $stdObj->name = "Demo"; $stdObj->age = 20; echo $stdObj->notExist; // Will throw error : PHP Notice: Undefined property: stdClass::$notExist

Fix stdclass undefined property issue

$stdObj = new stdClass(); $stdObj->name = "Demo"; $stdObj->age = 20; echo isset($stdObj->notExist) ? "Property notExist is defined" : "Property notExist is NOT defined"; // Property notExist is NOT defined

Learn about Stdclass object Php foreach loop with Examples

Fetching values from stdclass object depends on object type. We don’t need looping for single dimensional object. We can fetch values like $obj->param.

We require looping through objects which is multidimensional or complex structure. Please check Stdclass object Php foreach loop for well explained about stdclass object looping with easy to understand examples.

Was this post helpful?

Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you

Источник

Класс stdClass

Пустой класс общего назначения с динамическими свойствами.

Объекты класса могут быть инициализированы с помощью оператора new или созданы с помощью преобразования в объект. Некоторые функции PHP также создают экземпляры этого класса, например, функции json_decode() , mysqli_fetch_object() или PDOStatement::fetchObject() .

Несмотря на отсутствие реализации магических методов __get()/__set(), класс позволяет использовать динамические свойства и не требует атрибута #[\AllowDynamicProperties] .

Это не базовый класс, поскольку в PHP нет понятия универсального базового класса. Однако можно создать пользовательский класс, который расширяет stdClass и в результате наследует функциональность динамических свойств.

Обзор классов

У класса нет методов или свойств по умолчанию.

Примеры

Пример #1 Создание в результате преобразования в объект

Результат выполнения данного примера:

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

Пример #2 Создание в результате работы функции json_decode()

Результат выполнения данного примера:

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

Пример #3 Объявление динамических свойств

Результат выполнения данного примера:

object(stdClass)#1 (2) < ["foo"]=>int(42) ["1"]=> int(42) >

User Contributed Notes 1 note

In PHP8 this has been changed

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;

Источник

Php is standard class

В этом разделе перечисляются стандартные предопределённые классы. Разнообразные модули определяют другие классы, которые описаны в соответствующей справочной информации.

Стандартные определённые классы

Эти классы определены вместе со стандартным набором функций, идущим со сборкой PHP.

Directory Создаётся функцией dir() . stdClass Пустой класс общего назначения, созданный в результате преобразования в объект или различных стандартных функций. __PHP_Incomplete_Class Возможно, создаётся функцией unserialize() . Exception ErrorException php_user_filter Closure Предопределённый окончательный класс Closure , используется для внутренней реализации анонимных функций. Generator Предопределённый окончательный класс Generator , используется для представления генераторов. ArithmeticError AssertionError DivisionByZeroError Error Throwable ParseError TypeError

Специальные классы

Следующие идентификаторы не могут использоваться в качестве имени класса, так как у них есть специальное назначение.

User Contributed Notes 7 notes

if you want a Dynamic class you can extend from, add atributes AND methods on the fly you can use this:
class Dynamic extends stdClass public function __call ( $key , $params ) if(!isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . get_class ( $this ). «::» . $key . «()» );
$subject = $this ->< $key >;
call_user_func_array ( $subject , $params );
>
>
?>

this will accept both arrays, strings and Closures:
$dynamic -> myMethod = «thatFunction» ;
$dynamic -> hisMethod = array( $instance , «aMethod» );
$dynamic -> newMethod = array( SomeClass , «staticMethod» );
$dynamic -> anotherMethod = function() echo «Hey there» ;
>;
?>

then call them away =D

If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I’d advise you to implement ::__set_state().

/**
* An implementation of var_export() that is compatible with instances
* of stdClass.
* @param mixed $variable The variable you want to export
* @param bool $return If used and set to true, improved_var_export()
* will return the variable representation instead of outputting it.
* @return mixed|null Returns the variable representation when the
* return parameter is used and evaluates to TRUE. Otherwise, this
* function will return NULL.
*/
function improved_var_export ( $variable , $return = false ) if ( $variable instanceof stdClass ) $result = ‘(object) ‘ . improved_var_export ( get_object_vars ( $variable ), true );
> else if ( is_array ( $variable )) $array = array ();
foreach ( $variable as $key => $value ) $array [] = var_export ( $key , true ). ‘ => ‘ . improved_var_export ( $value , true );
>
$result = ‘array (‘ . implode ( ‘, ‘ , $array ). ‘)’ ;
> else $result = var_export ( $variable , true );
>

if (! $return ) print $result ;
return null ;
> else return $result ;
>
>

// Example usage:
$obj = new stdClass ;
$obj -> test = ‘abc’ ;
$obj -> other = 6.2 ;
$obj -> arr = array ( 1 , 2 , 3 );

improved_var_export ((object) array (
‘prop1’ => true ,
‘prop2’ => $obj ,
‘assocArray’ => array (
‘apple’ => ‘good’ ,
‘orange’ => ‘great’
)
));

/* Output:
(object) array (‘prop1’ => true, ‘prop2’ => (object) array (‘test’ => ‘abc’, ‘other’ => 6.2, ‘arr’ => array (0 => 1, 1 => 2, 2 => 3)), ‘assocArray’ => array (‘apple’ => ‘good’, ‘orange’ => ‘great’))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn’t formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().

There comes improved version of amazing snippet posted by (spark at limao dot com dot br) which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6

class Dynamic extends \ stdClass
public function __call ( $key , $params )
if ( ! isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . __CLASS__ . «::» . $key . «()» );
>

$dynamic = new Dynamic ();
$dynamic -> anotherMethod = function () echo «Hey there» ;
>;
$dynamic -> randomInt = function ( $min , $max ) return mt_rand ( $min , $max ); // random_int($min, $max); // >;

var_dump (
$dynamic -> randomInt ( 1 , 11 ),
$dynamic -> anotherMethod ()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array

class Dynamic extends \ stdClass
public function __call ( $key , $params )
if ( ! isset( $this ->< $key >)) throw new Exception ( «Call to undefined method » . __CLASS__ . «::» . $key . «()» );
>

return call_user_func_array ( $this ->< $key >, $params );
>
>

?>

Usage examples:
$dynamic = new Dynamic ();
$dynamic -> myMethod = «thatFunction» ;
$dynamic -> hisMethod = array( $dynamic , «randomInt» );
$dynamic -> newMethod = array( SomeClass , «staticMethod» );
$dynamic -> anotherMethod = function () echo «Hey there» ;
>;
$dynamic -> randomInt = function ( $min , $max ) return mt_rand ( $min , $max ); // random_int($min, $max); // >;

var_dump (
$dynamic -> randomInt ( 1 , 11 ),
$dynamic -> anotherMethod (),
$dynamic -> hisMethod ()
);

Источник

What is stdClass in PHP?

stdClass is a handy feature provided by PHP to create a regular class. It is a predefined ’empty’ class used as a utility class to cast objects of other types. It has no parents, properties, or methods. It also does not support magic methods and does not implement any interfaces.

Creating stdClass Object

In the following example, stdClass is used instead of an array to store details:

name= 'W3schools'; $obj->extension= 'In'; var_dump($object); ?>
object(stdClass)#1 (2) < ["name"]=>string(9) "W3schools" ["extension"]=> string(2) "In" >
  • If an object is converted to an object using stdClass, it is not modified.
  • If the given value is NULL, the new instance will also be empty.
  • Arrays convert to an object with properties named by keys and associated values. It’s like the alternative to associative arrays.
  • The member named scalar will contain the value for any other type of value.

Creating a stdClass Object by Type Casting

The following example shows that the value will be available in a member named Scalar when typecasting another type into an object:

object(stdClass)#1 (1) < ["scalar"]=>string(9) "W3schools" >

Convert an Array into an Object

In the following example, an array is converted to an object by typecasting:

'W3schools', 'Extension'=>'In', ); $obj= (object) $obj; var_dump($obj); ?>
object(stdClass)#1 (2) < ["name"]=>string(9) "W3schools" ["Extension"]=> string(2) "In" >

Convert an Object into an Array

In the following example, an object is converted to an array by typecasting:

name= 'W3schools'; $obj->extension= 'In'; $data = (array) $obj; print_r($data); ?>
Array( [name] => W3schools [extension] => In )

PHP differs from other object-oriented languages because classes in PHP do not automatically derive from any class. All PHP classes are standalone unless they are explicitly extended from another class. Here you can think of defining a class that expands stdClass, but it won’t give you any benefit because stdClass does nothing.

Источник

Оцените статью