Black technical details of how PHP objects are converted to arrays

Source: Internet
Author: User
Usually in PHP, it takes a bit of effort to work with an array of objects.
But here today, I'm telling you a so-easy black technology to solve this problem.

<?php/** * Created by Phpstorm. * USER:ZRJ * date:17-10-20 * Time: PM 8:08 */declare (Strict_types=1);//Open strong Type mode class person{public    $name;    public $age;    Public function __construct (string $name, int $age)    {        $this->name = $name;        $this->age = $age;    }} $jack = new Person (' Jack '); Echo Print_r ($jack, true); echo "<p>";//object to array $jack = Json_decode (Json_encode ($jack) , true); Echo Print_r ($jack, true);

Let's look at the results:

Person Object (    [name] + Jack    [age] + =) Array (    [name] + Jack    [age] + 18)

Thinking Analysis:

    1. The object is first json_encode processed into a JSON string.

    2. The converted JSON string is json_decode processed.

      Json_decode (Json_encode ($obj), true);


Advantages: Simple and quick.

Disadvantage: Double-fold memory is consumed.

The correct get posture:

The object itself occupies memory hours and can be used directly.

When the object itself occupies a large memory (such as thousands of records to form a DataSet object), twice times of memory may result in exceeding the memory limit of PHP and an exception occurs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.