以下PHP用于JavaScript文件进行的AJAX调用。
首先,基础类-
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';
}
}
现在,由两个单独的JS文件共享并调用方法的PHP-
// $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;
由于当前已设置(针对上面的启用行),因此回显:radius is nonsense
。三角形JS脚本只询问名称和边,而不询问半径。同样,圆形JS脚本只询问名称和半径,不询问边。因此,这有效。但是,我正在尝试使用数组作为查找来替换IF代码块,如下所示:
$array = [
'name' => $object->GetName(),
'sides' => $object->GetSides(),
'radius' => $object->GetRadius()
];
$data = $array[$action];
echo $data;
但这会导致Fatal error: Call to undefined method Circle::GetSides()
。可以解决这个问题吗?
答案 0 :(得分:0)
只需为该方法的不存在情况添加一个魔术方法。
也将此添加到Triangle
<?php
class Circle
{
public function __call($name, $arguments)
{
return '';
}
public function GetName()
{
return 'name is circle';
}
public function GetRadius()
{
return 'radius is nonsense';
}
}
有关here重载的PHP文档
答案 1 :(得分:0)
一种可行的替代方法是在查找数组中使用method_exists(),如下所示:
$array = [
'name' => method_exists($object, 'GetName') ? $object->GetName() : '',
'sides' => method_exists($object, 'GetSides') ? $object->GetSides() : '',
'radius' => method_exists($object, 'GetRadius') ? $object->GetRadius() : ''
];