简体   繁体   English

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

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

I just want to create function just like getFieldname() that is in magento. 我只想创建像magento中的getFieldname()一样的函数。

For Ex: 对于Ex:

In Magento 在Magento

getId() - returns value of ID field getId() - 返回ID字段的值

getName() - returns value of Name field getName() - 返回Name字段的值

How can I create like that function? 我怎样才能创建这样的功能? Kindly help me in this case.. 在这种情况下请帮助我..

I want to do just Like Below code, 我想做的就像下面的代码,

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();

Check the implementation of Varien_Object , the __call method is probably what you are looking for, I think. 检查Varien_Object的实现,我认为__call方法可能正是你要找的。 http://freegento.com/doc/de/d24/_object_8php-source.html http://freegento.com/doc/de/d24/_object_8php-source.html

This will basically "capture" any non-existing method calls and if they are in the shape $this->getWhateverField , will try to access that property. 这将基本上“捕获”任何不存在的方法调用,如果它们的形状$this->getWhateverField ,则会尝试访问该属性。 With minor tweaks should work for your purposes. 稍作调整应该适合您的目的。

You can use the magic method __call to solved your situation 您可以使用魔术方法 __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();

?>

You can read more about __call in: 您可以在以下位置阅读有关__call更多信息:

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

See if this is what you want: 看看这是不是你想要的:

Your class should be inherited from another class (Super class) which defines your required methods. 您的类应该从另一个定义所需方法的类(超类)继承。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM