Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chuyển đối tượng (Object) thành mảng (Array) trong PHP

Hai cách phổ biến chuyển object thành associative array:

Cách 1: json_encode + json_decode (Khuyên dùng)

<?php
class Student {
    public function __construct($first, $last) {
        $this->firstname = $first;
        $this->lastname = $last;
    }
}
$obj = new Student("Alex", "Stokes");
$arr = json_decode(json_encode($obj), true);
var_dump($arr);
// array(2) { ["firstname"]=> "Alex", ["lastname"]=> "Stokes" }
?>

Ưu: Xử lý tốt nested object, property public/protected. Nhược: Bỏ qua property private của class cha (nếu có).

Cách 2: Type Casting (Ép kiểu)

<?php
class Bag {
    public function __construct($i1, $i2, $i3) {
        $this->item1=$i1; $this->item2=$i2; $this->item3=$i3;
    }
}
$obj = new Bag("Books", "Ball", "Pens");
$arr = (array) $obj;
var_dump($arr);
// array(3) { ["item1"]=> "Books", ["item2"]=> "Ball", ["item3"]=> "Pens" }
?>

Ưu: Nhanh, đơn giản. Nhược: Key của property private sẽ có tiền tố "\0ClassName\0", property protected có "\0*\0".