PHPThere are many "ready-made classes", one of which is called the "built-in standard class". There is nothing "inside" this class.
class stdclass{ }
<?php$obj1 = new stdclass(); var_dump($obj1);class A{}$obj2 = new A(); var_dump($obj2);?>
Running result:
object(stdClass)[1]object(A)[2]
You can see that it is no different from the ordinary class.
The built-in standard class is used to store some temporary simple data, such as:
$obj1->pp1 = 1;$obj2->port = '3306';
It can also be used to store data during type conversion.
Other data types are converted to object types, and the result is: an object of the built-in standard class (stdclass) .
The syntax is:
$obj = (object)其他类型数据;
Convert the array to an object: the key name of the array is used as the attribute name, and the value is the corresponding value of the object.
#Note: The attributes of digital subscripted data elements after being converted into objects cannot be obtained through object syntax, so conversion is not recommended.
<?php $config = array( 'host' => "localhost", 'port' => 3306, 'user' => "root", 'pass' => "123", 'charset' => "utf8", 'dbname' => "yeoman", ); $obj1 = (object)$config; var_dump($obj1); echo "<br />单独取出user:" . $obj1->user;?>
Running result:
object(stdClass)[1] public 'host' => string 'localhost' (length=9) public 'port' => int 3306 public 'user' => string 'root' (length=4) public 'pass' => string '123' (length=3) public 'charset' => string 'utf8' (length=4) public 'dbname' => string 'yeoman' (length=6) 单独取出user:root
However, there are subscript elements in the array. If they are converted into objects, they cannot be obtained through object syntax.
<?php $arr = array('pp1' => 1, 5 => 12); $obj2 = (object)$arr; var_dump($obj2); echo "<br />单独取出pp1:" . $obj2->pp1;//echo "<br />单独取出5:" . $obj2->5;//会报错!?>
Running result:
$arr = array('pp1' => 1, 5 => 12); $obj2 = (object) $arr; var_dump($obj2); echo "<br />单独取出pp1:" . $obj2->pp1;//echo "<br />单独取出5:" . $obj2->5;//会报错!?>
nullConverted to object: empty object
$obj = (object)null;
Convert other scalar data to objects: the attribute name is fixed "scalar", and the value is the value of the variable
<?php$v1 = 1; $v2 = 2.2; $v3 = "abc"; $v4 = true; $objv1 = (object) $v1; //整型转为对象类型 $objv2 = (object) $v2; //浮点型转为对象类型 $objv3 = (object) $v3; //字符串型为对象类型 $objv4 = (object) $v4; //布尔转为对象类型 var_dump($objv1); echo "<br />"; var_dump($objv2); echo "<br />"; var_dump($objv3); echo "<br />"; var_dump($objv4); echo "<br />";
The running result is:
object(stdClass)[1] public 'scalar' => int 1 object(stdClass)[2] public 'scalar' => float 2.2 object(stdClass)[3] public 'scalar' => string 'abc' (length=3) object(stdClass)[4] public 'scalar' => boolean true
The above is the detailed content of PHP object-oriented - built-in standard classes and ordinary data types converted to object types. For more information, please follow other related articles on the PHP Chinese website!