douyin2435 2018-10-24 00:25
浏览 42
已采纳

使用数组作为动态对象实例的查找

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?

  • 写回答

2条回答 默认 最新

  • dreamice2013 2018-10-24 00:44
    关注

    just add a magic method for the non-existence case of the method.

    Also add this to Triangle

    <?php
    
    class Circle
    {
        public  function __call($name, $arguments)
        {
            return '';
        }
    
        public function GetName()
        {
            return 'name is circle';
        }
    
        public function GetRadius()
        {
            return 'radius is nonsense';
        }
    }
    

    PHP Docs on overloading here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大