Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active September 9, 2022 11:12
Show Gist options
  • Save adamwathan/88df91e4212935546861 to your computer and use it in GitHub Desktop.
Save adamwathan/88df91e4212935546861 to your computer and use it in GitHub Desktop.
Structs in PHP
<?php
// Wow this whole thing is horrible
class Struct
{
public function __construct($properties)
{
foreach ($properties as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
public function __get($key)
{
return $this->{$key};
}
public function __call($key, $args)
{
$struct = clone $this;
$struct->{$key} = $args[0];
return $struct;
}
}
// Structs just extend Struct and define the necessary properties
class Point extends Struct
{
protected $x;
protected $y;
}
// Instantiate by using an array to simulate named parameters
$point = new Point(['x' => 5, 'y' => 10]);
// Mutating a struct returns a new struct
$new_point = $point->y(12);
var_dump($point == $new_point); // false
// Two points with the same properties are (loosely) the same
$same_point = new Point(['x' => 5, 'y' => 10]);
var_dump($point == $same_point); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment