可以使用对象的属性和方法来提取数据。
如果对象属性是公共的,你可以直接使用箭头(->)操作符来访问该属性。例如:
class Person {
public $name = "John";
public $age = 30;
}
$person = new Person();
echo $person->name; // 输出 "John"
echo $person->age; // 输出 30
如果对象属性是私有的,你需要在对象的方法内部访问该属性。通常使用 Getter 和 Setter 方法来实现这个过程。例如:
class Person {
private $name = "John";
private $age = 30;
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$person = new Person();
echo $person->getName(); // 输出 "John"
echo $person->getAge(); // 输出 30
除了 Getter 和 Setter 方法,还可以使用魔术方法 get() 和 set() 来动态获取或设置对象属性的值。例如:
class Person {
private $data = [
"name" => "John",
"age" => 30
];
public function __get($name) {
return $this->data[$name];
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$person = new Person();
echo $person->name; // 输出 "John"
echo $person->age; // 输出 30
$person->name = "Peter";
$person->age = 25;
echo $person->name; // 输出 "Peter"
echo $person->age; // 输出 25