无涯教程-PHP - get_object_vars()函数

get_object_vars() - 语法

get_object_vars ( $object);

此函数获取给定对象的属性。

Sr.NoParameter & Description
1

object

对象实例。

get_object_vars() - 返回值

它返回指定对象的已定义对象属性的关联数组。如果尚未为属性赋值,则将返回空值。

get_object_vars() - 示例

<?php
   class Point2D {
      var $x, $y;
      var $label;
      
      function Point2D($x, $y) {
         $this->x=$x;
         $this->y=$y;
      }
      
      function setLabel($label) {
         $this->label=$label;
      }
      
      function getPoint() {
         return array("x" => $this->x, "y" => $this->y, "label" => $this->label);
      }
   }
   $p1=new Point2D(1.233, 3.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
)

PHP 中的 get_object_vars()函数 - 无涯教程网无涯教程网提供get_object_vars() - 语法 get_object_vars ( $object );此函数获取给定对象的属性。...https://www.learnfk.com/php/php-function-get-object-vars.html

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值