The following PHP is used for AJAX calls made by JavaScript files.
First, the underlying classes -
class Triangle
{
public function GetName()
{
return 'name is triangle';
}
public function GetSides()
{
return 'number of sides is three';
}
}
class Circle
{
public function GetName()
{
return 'name is circle';
}
public function GetRadius()
{
return 'radius is nonsense';
}
}
Now, the PHP that is shared by two separate JS files and calls the methods -
// $caller = 'triangle';
// $action = 'name';
// $action = 'sides';
$caller = 'circle';
// $action = 'name';
$action = 'radius';
$objects = [
'triangle' => new Triangle(),
'circle' => new Circle()
];
$object = $objects[$caller];
if ($action == 'name'):
$data = $object->GetName();
elseif ($action == 'sides'):
$data = $object->GetSides();
elseif ($action == 'radius'):
$data = $object->GetRadius();
endif;
echo $data;
As it's currently set up (for the enabled lines above) this echoes out: radius is nonsense
. The triangle JS script only ever asks for name and sides, never for radius. Similarly, the circle JS script only ever asks for name and radius, never for sides. So, this works. However, I'm trying to use an array as a lookup to replace the IF code block like so:
$array = [
'name' => $object->GetName(),
'sides' => $object->GetSides(),
'radius' => $object->GetRadius()
];
$data = $array[$action];
echo $data;
But this results in Fatal error: Call to undefined method Circle::GetSides()
. Can this be fixed and if so, how?