douyin2435 2018-10-23 16: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-23 16: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部