无忧站长 >

怎么使用stdClass Object

2019-11-01 14:45:28 
Array (
[0] => stdClass Object (
[term_id] => 3
[name] => apache
[slug] => apache
[term_group] => 0
[term_taxonomy_id] => 3
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 3
[category_count] => 1
[category_description] =>
[cat_name] => apache
[category_nicename] => apache
[category_parent] => 0 )

[1] => stdClass Object (
[term_id] => 1
[name] => PHP
[slug] => php
[term_group] => 0
[term_taxonomy_id] => 1
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 1
[category_count] => 1
[category_description] =>
[cat_name] => PHP
[category_nicename] => php
[category_parent] => 0 ) )
二维数组stdClass Object是一组json对象,如果要调用里面的数据,就要这样调用,
foreach($categories as $key => $value){
 $cat = $value->term_id;
 $name = $value->name;
}

stdclass在php中是预定义的几个类之一,是zent保留的一个类。实际上它是PHP提供的一个基类,就是一个空白的类,里面什么都没有,我们可以实例化它,然后定义一系列的变量,通过它来进行变量的传递(很多php程序员用它来传递一系列变量的值,而同时又懒得去创建一个自己的类)。但是,由于实例化后不能添加方法,只能传递属性。因为,一旦类被实列化以后,就不能在添加方法了。
stdclass可以作为基类使用,其最大特点是,(其派生类)可以自动添加成员变量,而无须在定义时说明。
一切php变量都是stdClass的实例。
使用方法:
1、使用stdclass:
   $andy = array();
   $andy = (object)$andy;
   $andy->a = 1;
   $andy->b = 2;
   $andy->c = 3;
这样数量a、b、c就填进了stdclass里面。这样要省事,因为新建空对像却要$andy = new Andy; 而且还得先有个class Andy{}。又如:
<?php
$a = new stdClass();
$a->id = '11 ';
$a->username = 'me';
print_r($a);
?>
将会输出:stdClass Object ( [id] => 11 [username] => me ) 。
很多时候用这种方法取代数组的使用,只不过是换一种语法形式。
2、读取:
stdClass Object
(
  [getWeatherbyCityNameResult] => stdClass Object
    (
      [string] => Array
         (
           [0] => 四川
           [1] => 成都
           [2] => 56294
           [3] => 56294.jpg
           [4] => 2009-5-17 13:52:08
           [5] => 26℃/19℃
           [6] => 5月17日 阴转阵雨
         )
    )
)
其实和array差不多,只是访问方式改变一点就行,我们一般习惯使用array['key']这种方式来访问数组。
对于这种stdClass来说,如上例,$weather->getWeatherbyCityNameResult->string[0]可以这样来访问属性,这个将得到结果“四川”。
3、实例化,new。
对比这两个代码:
<?php
$a = array(1=>2,2=>3);
$a = (object)$a;
$a->id = '11 ';
$a->username = 'me';
print_r($a);
?>
将输出:stdClass Object ( [1] => 2 [2] => 3 [id] => 11 [username] => me ) 。
<?php
$a = array(1=>2,2=>3);
$a = (object)$a;
$a = new stdClass();
$a->id = '11 ';
$a->username = 'me';
print_r($a);
?>
将输出:stdClass Object ( [id] => 11 [username] => me ) 。
原来用new实例化后,前面的数组清空,只留下后面添加进来的,如果不实例化,stdClass将保留所有元素。
phpjson