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!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

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.

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 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

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

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.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.