라이브러리
[PHP] Serializable::serialize - 객체의 문자열 표현
PHP의 Serializable::serialize
PHP의 `Serializable` 인터페이스는 객체를 serialize 할 수 있는지 여부를 확인하는 데 사용됩니다. serialize은 객체의 속성을 문자열로 변환하여 저장하거나 전송하는 것을 의미합니다.
Serializable 인터페이스
Serializable 인터페이스는 PHP 5.1.0부터 사용할 수 있습니다. 이 인터페이스를 구현하려면 `__sleep()` 메서드를 구현해야 합니다. `__sleep()` 메서드는 serialize 할 속성을 배열로 반환합니다.
# 예제 1: Serializable 인터페이스 구현
#hostingforum.kr
php
class Person implements Serializable {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function serialize() {
return serialize(array($this->name, $this->age));
}
public function unserialize($serialized) {
list($this->name, $this->age) = unserialize($serialized);
}
}
$person = new Person('John Doe', 30);
$serialized = serialize($person);
echo $serialized . "
";
$unserialized = unserialize($serialized);
echo $unserialized->name . "
";
echo $unserialized->age . "
";
__sleep() 메서드
`__sleep()` 메서드는 serialize 할 속성을 배열로 반환합니다. 이 메서드는 `serialize()` 메서드와 함께 사용됩니다.
# 예제 2: __sleep() 메서드 구현
#hostingforum.kr
php
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function __sleep() {
return array('name', 'age');
}
public function __wakeup() {
// 객체가 unserialize 될 때 호출됩니다.
}
}
$person = new Person('John Doe', 30);
$serialized = serialize($person);
echo $serialized . "
";
$unserialized = unserialize($serialized);
echo $unserialized->name . "
";
echo $unserialized->age . "
";
__wakeup() 메서드
`__wakeup()` 메서드는 객체가 unserialize 될 때 호출됩니다. 이 메서드는 `__sleep()` 메서드와 함께 사용됩니다.
참고
- PHP의 `Serializable` 인터페이스는 객체를 serialize 할 수 있는지 여부를 확인하는 데 사용됩니다.
- `__sleep()` 메서드는 serialize 할 속성을 배열로 반환합니다.
- `__wakeup()` 메서드는 객체가 unserialize 될 때 호출됩니다.
- `serialize()` 메서드는 객체의 속성을 문자열로 변환하여 저장하거나 전송하는 것을 의미합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.