stdclassphp
❶ php的stdClass類詳解及幾種數組對象轉換方法
一、stdClass數組轉對象
$arr=array();
$arr['a']=1;
$arr['b']=2;
$arr['c']=3;
$object=newstdClass;
foreach($arras$key=>$value){
$object->$key=$value;
}
var_mp($object);
結果輸出如下:
object(stdClass)#1(3){
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
}
二、對象轉數組
functionobject_to_array($obj)
{
$_arr=is_object($obj)?get_object_vars($obj):$obj;
foreach($_arras$key=>$val)
{
$val=(is_array($val)||is_object($val))?object_to_array($val):$val;
$arr[$key]=$val;
}
return$arr;
}
三、ArrayObject方法數組轉對象
$arr=array('key1'=>'test1','key2'=>'test2');
var_mp(newArrayObject($arr));
結果輸出如下:
object(ArrayObject)#1(1){
["storage":"ArrayObject":private]=>
array(2){
["key1"]=>
string(5)"test1"
["key2"]=>
string(5)"test2"
}
}
❷ php 中如何得到一個對象的類型
得到一個對象的類型,使用gettype()函數:
<?php
echogettype(1);//輸出integer
echogettype(array());//輸出array
得到一個對象是哪個類的實例,使用get_class()函數:
<?php
$o=newstdClass();
echoget_class();//輸出stdClass
得到一個類或對象的方法和屬性,要使用反射:
<?php
classMyClass{
public$var;
publicfunctionfoo(){}
}
$ref=newReflectionClass('MyClass');
$ref->getProperties();//會返回一組對象,用法參考PHP手冊
$ref->getMethods();//會返回一組對象,用法參考PHP手冊
$obj=newMyClass();
$ref=newReflectionObject($obj);
$ref->getProperties();
$ref->getMethods();
❸ PHP中stdClass Object怎麼獲取指定數據
這是json_decode出來的對象
$result = json_decode($jsonstr);
echo $result->Code;
echo $result->Message;
json_decode支持轉為數組或對象, 轉為數組的時候第二個參數傳true
$result = json_decode($jsonstr,true);
echo $result['Code'];
echo $result['Message'];
❹ php中 stdclass object是什麼
stdClass在PHP5才開始被流行。而PHP stdClass也是zend的一個保留類。似乎沒有其他作用。也幾乎沒有任何說明。
或者,我們可以這么理解:PHP stdClass是PHP的一個基類,所有的類幾乎都繼承這個類,所以任何時候都可以被new,可以讓這個變數成為一個object。同時,這個基類又有一個特殊的地方,就是沒有方法。
凡時用new stdClass()的變數,都不可能會出現$a->test()這種方式的使用。
說簡單的一些,stdClass()就是一個程序員實現提前聲明的類,也就是說我們可以隨時讓一個變數成為一個類對象的實例而不需要先聲明類才能創建類對象的實例。
❺ php中怎樣訪問對象中名字叫0的成員
在別的地方看到了答案,貼到這里讓更多同學們學習一下吧
$a = new \stdClass();
$a->{0} = "test";
var_mp($a); //object(stdClass)#1 (1) { ["0"]=> string(4) "test" }
echo $a->{0}; //test
❻ php的smarty出錯,Call to undefined method stdClass::createTemplate()
stdclass在php中是預定義的幾個類之一,是zent保留的一個類。實際上它是PHP提供的一個基類,就是一個空白的 類,裡面什麼都沒有,我們可以實例化它,然後定義一系列的變數,通過它來進行變數的傳遞(很多php程序員用它來傳遞一系列變數的值,而同時又懶得去創建 一個自己的類)。但是,由於實例化後不能添加方法,只能傳遞屬性。因為,一旦類被實列化以後,就不能在添加方法了。--from