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 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口