We have already seen how we can create an object in PHP in a simple way. Now let’s see how we can create an object from an array in PHP. That is, the object and the properties will be defined within an array.
The object that we are going to create in PHP represents a book with the following properties:
Title - The Cursed Legions Author - Santiago Posteguillo Editorial - Editions B Publication Date - 2008
The first thing we will do is define the array in PHP with object properties:
$miarray = array("title"=>"The Cursed Legions",
"author" => "Santiago Posteguillo",
"editorial" => "Editions B",
"publication date" => 2008);
We see that the index value of the array elements is the name of the property and the index value in the array is the value of said property.
In the previous code we have created and inserted the values of the array directly into its instantiation. Although we could go in parts, if it is easier for you:
$myarray = array();
$miarray["title"] = "The Cursed Legions";
$miarray["author"] = "Santiago Posteguillo";
$miarray["editorial"] = "Editions B";
$myarray["publicationdate"] = 2008;
If we check the structure of the variable $miarray, we will see that it is obviously of type array:
array(4) { ["title"]=> string(21) "The Cursed Legions" ["author"]=> string(20) "Santiago Posteguillo" ["editorial"]=> string(11) "Editions B" ["publicationdate"]=> int(2008) }
The next thing we will do is transform the array into an object. To do this, we force type conversion by prefixing the type we want to convert to in an assignment. In this case we create the object from an array forcing the type object.
$book = (object)$myarray;
If we now check the structure of $book we will see the following:
object(stdClass)#1 (4) { ["title"]=> string(21) "The Cursed Legions" ["author"]=> string(20) "Santiago Posteguillo" ["editorial"]=> string(11) "Editions B" ["publicationdate"]=> int(2008) }
We have already seen how to create an object from an array in PHP.