Php array conversion to object PHP-ConvertArraytoObjectwithstdClass

Source: Internet
Author: User
Tags type casting
ThePHPstdClass () issomethingthatisn & amp; #39; twell?entedbutiwilltrytoshedsomelight=thematter. stdClassisadefaultPHPobjectwhichhasnopredefi...

 

The PHP stdClass () is something that isn' t well known ented but I will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. the name stdClass is used internally by Zend and is reserved. so that means that you cannot define a class named stdClass in your PHP code.

It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which until CT to take an object as an argument. an even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.

Here's an example below that converts an array to an object below. This method is called Type Casting.

$ Person = array (

'Firstname' => 'Richard ',

'Lastname' => 'case'

);

 

$ P = (object) $ person;

Echo $ p-> firstname; // Will print 'Richard'

?>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.