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