How to convert object into array in php
In PHP development, we often need to convert between objects and arrays. Common application scenarios require converting objects into arrays. PHP provides many methods to complete this conversion process, the most commonly used method is to convert the object into an array through a caster.
In PHP, when we convert an object into an array, the object's attribute name is automatically used as the key name, and the attribute value is stored in the array as the key value. At the same time, PHP can also selectively convert the private, protected, and public properties of an object.
Let’s learn how to convert objects into arrays through examples:
class BlogPost { private $title; private $content; protected $publishedAt; public function __construct($title, $content) { $this->title = $title; $this->content = $content; $this->publishedAt = date('Y-m-d H:i:s'); } } $post = new BlogPost('PHP Object Convert Array', 'PHP 中对象转换数组的实现'); $array_post = (array) $post; // 将对象转换为数组 print_r($array_post);
In the above example, we defined a BlogPost
class, which has three attributes: title
, content
, and publishedAt
. Among them, title
and content
are private properties, and publishedAt
is a protected property. In the constructor of the class, we set the $title
and $content
properties, and by default the $publishedAt
property is set to the current time.
Next, we instantiate the BlogPost
class and cast it to an array $array_post
. Finally, we use the print_r
function to print the contents of the $array_post
array. You can see the output as follows:
Array ( [BlogPosttitle] => PHP Object Convert Array [BlogPostcontent] => PHP 中对象转换数组的实现 [*publishedAt] => 2021-09-14 15:10:34 )
You can find that when we use (array )
When performing type conversion, the object's attribute name will be prefixed with the class name. This is because in PHP, the same attribute name can only appear once. In order to prevent attribute name conflicts, PHP automatically adds the class name as a prefix. At the same time, we can also access the properties of the object through arrays, such as echo $array_post['BlogPosttitle'];
which can output PHP Object Convert Array
.
It should be noted that when there are private properties and protected properties in the object, they are inaccessible by default after being converted to an array, but if we want to add them to the array, we can passReflectionClass
class to implement:
class BlogPost { private $title; private $content; protected $publishedAt; public function __construct($title, $content) { $this->title = $title; $this->content = $content; $this->publishedAt = date('Y-m-d H:i:s'); } } $post = new BlogPost('PHP Object Convert Array', 'PHP 中对象转换数组的实现'); $reflection_class = new ReflectionClass($post); $properties = $reflection_class->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE); // 获取所有属性 $array_post = []; foreach ($properties as $property) { $property->setAccessible(true); // 设置属性可访问 $array_post[$property->getName()] = $property->getValue($post); // 将属性及属性值添加到数组中 } print_r($array_post);
In the above example, we used the ReflectionClass
and ReflectionProperty
classes to get all properties of the object, including public properties , protected properties and private properties. Then set the attribute to be accessible through the setAccessible()
method, and finally add the attribute and attribute value to the array. The output result is as follows:
Array ( [title] => PHP Object Convert Array [content] => PHP 中对象转换数组的实现 [publishedAt] => 2021-09-14 15:10:34 )
In summary, PHP provides a variety of ways to The common way to convert an object into an array is to use the cast operator (array)
. At the same time, we can also selectively add private properties and protected properties to the array, which can be achieved through the ReflectionClass
class. No matter which method is used, you can easily convert objects into arrays for better processing and passing of object data.
The above is the detailed content of How to convert object into array in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.
