How to convert php object to array

WBOY
Release: 2023-05-07 14:52:07
Original
834 people have browsed it

In PHP, objects and arrays are very important data types, and they have their own characteristics and uses. During the development process, we often need to convert objects into arrays to facilitate data transmission and processing. This article will introduce in detail the conversion methods between PHP objects and arrays and their precautions.

1. The basic concept of PHP objects

In PHP, an object is the basis of object-oriented programming. It is an entity instantiated from a class and can be manipulated through methods and properties. it. The following is the basic syntax for creating an object:

class MyClass {
  public $name;
  public function sayHello() {
    echo "Hello, my name is " . $this->name;
  }
}

$obj = new MyClass();
$obj->name = "PHP";
$obj->sayHello();
Copy after login

In the above code, we first define a MyClass class, which has a public property $name and a public method sayHello, and then we create a MyClass object $obj, and assign its attribute $name to "PHP", and finally call the sayHello method of $obj to output the result.

2. Method of converting PHP object to array

Converting object to array is a relatively common operation. PHP provides two methods: forced type conversion and serialization (serialize).

  1. Forced type conversion

We can convert objects to arrays through (array) or get_object_vars(). Their principle is to convert the attributes in the object into the corresponding Array of key-value pairs.

class MyClass {
  public $name = "PHP";
  private $age = 20;
}
$obj = new MyClass();
$arr = (array) $obj;
var_dump($arr); //输出:array(2) { ["name"]=> string(3) "PHP" ["age"]=> int(20) }

$obj = new MyClass();
$arr = get_object_vars($obj);
var_dump($arr); //输出:array(1) { ["name"]=> string(3) "PHP" }
Copy after login

In the above code, we first define a MyClass class, which has a public attribute $name and a private attribute $age. Then we convert this object through (array) and get_object_vars() respectively. are arrays, and finally output their results.

It should be noted that when using forced type conversion, the value of the private attribute cannot be obtained, and only the public attribute can be converted successfully. If we need to convert private properties into arrays, we need to use ReflectionClass.

  1. Serialization

In PHP, serialization (serialize) refers to the process of converting an object or array into a string, while deserialization (unserialize) is Convert the string into the original object or array. We can implement serialization and deserialization through the serialize() and unserialize() functions.

class MyClass {
  public $name = "PHP";
  private $age = 20;
}
$obj = new MyClass();
$str = serialize($obj); //序列化对象
$arr = unserialize($str); //反序列化数组
var_dump($arr); //输出:object(MyClass)#2 (2) { ["name"]=> string(3) "PHP" ["age":"MyClass":private]=> int(20) }
Copy after login

In the above code, we first define a MyClass class, which has a public property $name and a private property $age, then we serialize the $obj object into a string $str, and then Then deserialize to get the array $arr and output the result.

It should be noted that when using serialization, the value of the private attribute can also be obtained, but when deserializing, you need to ensure that the class definition of the original object exists, otherwise unserialize(data): undefined class will appear Error with constant 'xxxx'.

3. Method of converting PHP array to object

In addition to converting objects to arrays, it is often necessary to convert arrays to objects. In PHP, we can achieve this through cast or json_decode() function.

  1. Forced type conversion

To convert an array into an object, you only need to assign the array to the object. The attribute name of the object is the key name of the array, and the attribute value is the key value of the array.

class MyClass {}
$arr = array('name' =>'PHP', 'age' =>20);
$obj = (object) $arr;
var_dump($obj); //输出:object(stdClass)#1 (2) { ["name"]=> string(3) "PHP" ["age"]=> int(20) }
Copy after login

In the above code, we first create an empty MyClass class, then define an array $arr, which contains two key-value pairs of 'name' and 'age', and then pass it through ( object) is cast to object $obj and outputs the result.

  1. json_decode()

We can also use the json_decode() function to convert the array into an object, and the implementation method is also very simple. Convert the array into a JSON string using the json_encode() function, and then use the json_decode() function to convert the JSON string into an object.

class MyClass {}
$arr = array('name' =>'PHP', 'age' =>20);
$json = json_encode($arr);
$obj = json_decode($json);
var_dump($obj); //输出:object(stdClass)#1 (2) { ["name"]=> string(3) "PHP" ["age"]=> int(20) }
Copy after login

In the above code, we first create an empty MyClass class, then define an array $arr, which contains two key-value pairs of 'name' and 'age', and then pass it through json_encode () function into a JSON string $json, then use the json_decode() function to convert the JSON string into an object $obj, and output the result. It should be noted that json_decode() returns a PHP object by default instead of an array.

4. Some points that need attention

Although the conversion method between objects and arrays is very simple, there are still some things that need to be paid attention to during use.

  1. Private properties cannot be obtained through forced type conversion

When the object is converted into an array, the value of the private property cannot be obtained. You need to use ReflectionClass to obtain it. Otherwise, the error "Private property cannot be accessed in..." will appear.

  1. Serialization is a resource-consuming process

Although serialization is convenient and simple, when processing large amounts of data, serialization will occupy a lot of CPU and memory, so you need to pay attention to its consumption.

  1. json_decode() may return false

When an error occurs in parsing the JSON string, the json_decode() function may return false. If you need to use its results, you need to pay attention. Add error handling.

In short, conversion between objects and arrays is very commonly used in PHP, and can be achieved through forced type conversion and serialization. When application development requires frequent use of objects and arrays, mastering these skills will greatly improve work efficiency.

The above is the detailed content of How to convert php object to array. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template