Implementing struct using a PHP array

As we already know, a struct is a complex data type where we define multiple properties as a group so that we can use it as a single data type. We can write a struct using a PHP array and class. Here is an example of a struct using a PHP array:

$player = [ 
"name" => "Ronaldo",
"country" => "Portugal",
"age" => 31,
"currentTeam" => "Real Madrid"
];

It is simply an associative array with keys as string. A complex struct can be constructed using single or more constructs as its properties. For example using the player struct, we can use a team struct:

$ronaldo = [ 
"name" => "Ronaldo",
"country" => "Portugal",
"age" => 31,
"currentTeam" => "Real Madrid"
];

$messi = [
"name" => "Messi",
"country" => "Argentina",
"age" => 27,
"currentTeam" => "Barcelona"
];

$team = [
"player1" => $ronaldo,
"player2" => $messi
];

The same thing we can achieve using PHP Class. The example will look like:
Class Player {

public $name;
public $country;
public $age;
public $currentTeam;

}

$ronaldo = new Player;
$ronaldo->name = "Ronaldo";
$ronaldo->country = "Portugal";
$ronaldo->age = 31;
$ronaldo->currentTeam = "Real Madrid";

Since we have seen both ways of defining a struct, we have to choose either one of them to implement a struct. While creating an object might look more convenient, it is slower compared to array implementation. Where an array has an added advantage of speed, it also has a disadvantage as it takes more memory space compared to an object. Now we have to make the decision based on our preference.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset