I need to implement a function that will return the property 'name' of an object no matter how deeply it is embedded into other objects. I want to use dot notation to navigate through the hierarchy of objects.
Here is what I have so far:
#!/usr/bin/php
<?php
class Foo
{
public $name = 'This is foo';
public $Bar;
}
class Bar
{
public $name = 'This is bar';
public $Baz;
}
class Baz
{
public $name = 'This is baz';
}
function getName(Foo $foo, string $obj): string {
if (strpos($obj, '.')) {
$path = explode('.', $obj);
//There has to be a better way than having to explicitly handle each count!
switch (count($path)) {
case 2:
return $foo->{$path[1]}->name;
case 3:
return $foo->{$path[1]}->{$path[2]}->name;
}
}
return $foo->name;
}
$foo = new Foo();
$bar = new Bar();
$baz = new Baz();
$bar->Baz = $baz;
$foo->Bar = $bar;
echo getName($foo, 'Foo') . "\n";
echo getName($foo, 'Foo.Bar') . "\n";
echo getName($foo, 'Foo.Bar.Baz') . "\n";
?>
... I'm trying to find an elegant way to get rid of the switch statement and to support any number of levels ('Foo', 'Foo.Bar', 'Foo.Bar.Baz', [...], 'Foo.Bar.Baz.Boo.Far.Faz.[...]').
Replacing the '.'
by '->'
in $obj
clearly does not work. Any thoughts?