get_object_vars 返回由对象属性组成的关联数组

(PHP 4, PHP 5)

get_object_vars -- 返回由对象属性组成的关联数组

描述

array get_object_vars ( object obj )

返回由 obj 指定的对象中定义的属性组成的关联数组。

注: 在 PHP 4.2.0 之前的版本中,如果在 obj 对象实例中声明的变量没有被赋值,则它们将不会在返回的数组中。而在 PHP 4.2.0 之后,这些变量作为键名将被赋予 NULL 值。

例子 1. 使用 get_object_vars()

<?php
class Point2D {
    var 
$x$y;
    var 
$label;

    function 
Point2D($x$y) {
        
$this->$x;
        
$this->$y;
    }

    function 
setLabel($label) {
        
$this->label $label;
    }

    function 
getPoint() {
        return array(
"x" => $this->x,
                     
"y" => $this->y,
                     
"label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.2333.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));

?>
上边的程序将输出:
Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

参见 get_class_methods()get_class_vars()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你要获取 PHP对象Object)中的属性(Property),可以使用 PHP 中的魔术方法 __get()。这个方法会在试图获取一个未定义或不可见属性时自动调用。 示例代码: ```php class MyClass { private $myProperty = 'Hello'; public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } else { return null; } } } $myObject = new MyClass(); echo $myObject->myProperty; // 输出:Hello ``` 如果你需要获取对象中所有属性,包括私有属性,可以使用 `get_object_vars()` 函数。示例代码: ```php class MyClass { private $myProperty = 'Hello'; public $publicProperty = 'World'; } $myObject = new MyClass(); $vars = get_object_vars($myObject); print_r($vars); ``` 输出: ``` Array ( [myProperty] => Hello [publicProperty] => World ) ``` 如果对象中包含其他对象,可以使用 `json_encode()` 将对象转换为 JSON 字符串,然后再使用 `json_decode()` 将字符串转换为数组,就可以获取对象中的属性了。示例代码: ```php class SubClass { public $subProperty = 'Sub Value'; } class MyClass { public $myProperty = 'My Value'; public $subObject; public function __construct() { $this->subObject = new SubClass(); } } $myObject = new MyClass(); $jsonString = json_encode($myObject); $array = json_decode($jsonString, true); print_r($array); ``` 输出: ``` Array ( [myProperty] => My Value [subObject] => Array ( [subProperty] => Sub Value ) ) ``` 注意:使用 `json_encode()` 和 `json_decode()` 转换对象时,对象中的私有属性将被忽略。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值