get_object_vars()

array get_object_vars(object $obj)返回$obj对象的所有的非静态属性。

eg:

<?php
class  Animal
{
    public $cat = 4;
    protected $fox = 4;
    private $pig = 3;
    private $mouse = 3;
    public function PrintNum()
    {
        print_r(get_object_vars($this));
        print("<br>");
    }
}
    $a = new Animal;
    $a->PrintNum();
    print_r(get_object_vars($a));
?>

输出:Array ( [cat] => 4 [fox] => 4 [pig] => 3 [mouse] => 3 ) 
Array ( [cat] => 4 )


  • 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、付费专栏及课程。

余额充值