Struct Embedding in PHP
PHP supports object-oriented programming, which we can use to demonstrate a concept similar to struct embedding. We’ll use inheritance to showcase a similar behavior.
<?php
class Base {
public $num;
public function __construct($num) {
$this->num = $num;
}
public function describe() {
return sprintf("base with num=%d", $this->num);
}
}
// Container inherits from Base
class Container extends Base {
public $str;
public function __construct($num, $str) {
parent::__construct($num);
$this->str = $str;
}
}
// Main execution
$co = new Container(1, "some name");
// We can access the base's properties directly on $co
printf("co={num: %d, str: %s}\n", $co->num, $co->str);
// We can also access the base's properties using parent::
echo "also num: " . $co->num . "\n";
// Since Container extends Base, the methods of Base are also available to Container
echo "describe: " . $co->describe() . "\n";
// PHP doesn't have interfaces in the same way as Go, but we can use abstract classes
abstract class Describer {
abstract public function describe();
}
// We can implement the abstract class to achieve a similar effect
class DescribableContainer extends Container {
public function describe() {
return parent::describe();
}
}
$d = new DescribableContainer(1, "some name");
echo "describer: " . $d->describe() . "\n";
To run this PHP script, save it as class-inheritance.php
and execute it using the PHP CLI:
$ php class-inheritance.php
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1
In this PHP example, we’ve used class inheritance to demonstrate a concept similar to struct embedding in Go. The Container
class extends the Base
class, which allows it to inherit properties and methods from Base
. This is analogous to embedding in Go, although the syntax and some behaviors differ.
We’ve also shown how to implement an abstract class (Describer
) to achieve a similar effect to Go’s interface implementation through embedding. In PHP, a class that extends an abstract class must implement all of its abstract methods.
While PHP doesn’t have a direct equivalent to Go’s struct embedding, inheritance and abstract classes provide ways to achieve similar compositional patterns and method implementations.