如何调用class中不存在的方法php?

How to call class methods that do not exist in php?

我只想创建像 magento 中的 getFieldname() 一样的功能。

例如:

在 Magento 中

getId() - returns ID 字段的值

getName() - returns Name 字段的值

如何创建类似的功能?在这种情况下请帮助我..

我想像下面的代码一样,

Class Called{
    $list=array();
    function __construct() {
        
        $this->list["name"]="vivek";
        $this->list["id"]="1";
    }
    function get(){
        echo $this->list[$fieldname];
    }

}

$instance=new Called();

$instance->getId();
$instance->getName();

看看这是不是你想要的:

您的 class 应该继承自另一个 class(超级 class),它定义了您需要的方法。

class Super {

    public function getId(){
        return $this->list["id"];
    }

    public function getName(){
        return $this->list["name"];
    }

}

class Called extends Super {

    var $list = array();

    function __construct() {

        $this->list["name"]="vivek";
        $this->list["id"]="1";
    }
}

$instance=new Called();

echo $instance->getId(); // 1
echo $instance->getName(); //vivek

检查 Varien_Object 的实现,我想 __call 方法可能就是您要找的。 http://freegento.com/doc/de/d24/_object_8php-source.html

这基本上会 "capture" 任何不存在的方法调用,如果它们的形状是 $this->getWhateverField,将尝试访问那个 属性。稍作调整即可达到您的目的。

你可以使用魔法 __call来解决你的问题

<?php
class Called
{
    private $list = array('Id' => 1, 'Name' => 'Vivek Aasaithambi');

    public function __call($name, $arguments) {
        $field = substr($name, 3);
        echo $this->list[$field];
    }
}

$obj = new Called();
$obj->getId();
echo "<br/>\n";
$obj->getName();

?>

您可以在以下位置阅读有关 __call 的更多信息:

http://php.net/manual/en/language.oop5.overloading.php#object.call