Structs in PHP

Our example demonstrates how to use structs to group data together to form records.

<?php

class Person {
    public $name;
    public $age;
    
    public function __construct($name) {
        $this->name = $name;
        $this->age = 42;
    }
}

function newPerson($name) {
    return new Person($name);
}

// This syntax creates a new object of the Person class
var_dump(new Person("Bob"));

// You can name the fields when initializing an object
$alice = new Person("Alice");
$alice->age = 30;
var_dump($alice);

// Omitted fields will be zero-valued (null in PHP)
$fred = new Person("Fred");
$fred->age = null;
var_dump($fred);

// Use a pointer-like behavior with an object
$ann = new Person("Ann");
$ann->age = 40;
var_dump($ann);

// Encapsulate new object creation in constructor functions
$jon = newPerson("Jon");
var_dump($jon);

// Access object fields with a dot
$sean = new Person("Sean");
$sean->age = 50;
echo $sean->name, "\n";

// Objects are mutable
$sean->age = 51;
echo $sean->age, "\n";

// Anonymous classes can be used for single-use value types
$dog = new class {
    public $name = "Rex";
    public $isGood = true;
};
var_dump($dog);
?>

To run the code, save it into a file named structs.php and then use the PHP interpreter to execute it.

$ php structs.php

This will output:

object(Person)#1 (2) {
  ["name"]=>
  string(3) "Bob"
  ["age"]=>
  int(42)
}
object(Person)#2 (2) {
  ["name"]=>
  string(5) "Alice"
  ["age"]=>
  int(30)
}
object(Person)#3 (2) {
  ["name"]=>
  string(4) "Fred"
  ["age"]=>
  NULL
}
object(Person)#4 (2) {
  ["name"]=>
  string(3) "Ann"
  ["age"]=>
  int(40)
}
object(Person)#5 (2) {
  ["name"]=>
  string(3) "Jon"
  ["age"]=>
  int(42)
}
Sean
50
51
object(class@anonymous)#6 (2) {
  ["name"]=>
  string(3) "Rex"
  ["isGood"]=>
  bool(true)
}