티스토리 뷰

배움/PHP

fromArray 함수

spaces25 2025. 8. 22. 10:51
반응형

🧩 예시로 이해하는 fromArray

✅ 1. 기본 사용 예

 
class User {
    public $name;
    public $email;

    public function fromArray(array $data) {
        if (isset($data['name'])) {
            $this->name = $data['name'];
        }
        if (isset($data['email'])) {
            $this->email = $data['email'];
        }
        return $this;
    }
}

🧪 사용법

 
$userData = [
    'name' => 'Alice',
    'email' => 'alice@example.com'
];

$user = (new User())->fromArray($userData);

echo $user->name;   // 출력: Alice
echo $user->email;  // 출력: alice@example.com

🔁 2. 팩토리 메서드 형태로 구현

fromArray를 정적(static) 메서드로 구현해서 객체를 생성하는 데도 자주 사용됩니다:

 
class Product {
    public $id;
    public $title;

    public static function fromArray(array $data) {
        $instance = new self();
        $instance->id = $data['id'] ?? null;
        $instance->title = $data['title'] ?? null;
        return $instance;
    }
}

🧪 사용 예

 
$productData = ['id' => 101, 'title' => 'Monitor'];

$product = Product::fromArray($productData);

echo $product->title;  // 출력: Monitor

🎯 사용 목적 요약

 

목적 설명
데이터 매핑 배열 데이터를 객체 속성에 쉽게 매핑
유연한 객체 생성 정적 메서드로 객체 생성 로직 분리
API/DB 등 외부 데이터 처리 외부 소스로부터 받은 배열 데이터를 모델 객체로 변환할 때 유용

✅ 팁

  • fromArray는 직렬화/역직렬화와 비슷한 역할을 합니다.
  • Laravel이나 Symfony 같은 프레임워크에서는 이와 비슷한 메서드들이 내장되어 있거나, 모델에서 자동으로 배열 ↔ 객체 변환이 지원되기도 합니다.
  • toArray() 메서드와 함께 쌍으로 사용하는 경우도 많습니다.
반응형

'배움 > PHP' 카테고리의 다른 글

Laravel Arr Class  (0) 2025.07.31
Eloquent 관계  (2) 2025.07.29
uniqid()  (0) 2025.07.16
curl_multi_init  (0) 2025.07.15
call_user_func  (0) 2025.07.14
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함