Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I just want to create function just like getFieldname() that is in magento.

For Ex:

In Magento

getId() - returns value of ID field

getName() - returns value of Name field

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();
like image 971
Vivek Aasaithambi Avatar asked Feb 24 '26 23:02

Vivek Aasaithambi


2 Answers

You can use the magic method __call to solved your situation

<?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:

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

like image 60
Adrian Cid Almaguer Avatar answered Feb 26 '26 14:02

Adrian Cid Almaguer


Check the implementation of Varien_Object, the __call method is probably what you are looking for, I think. 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. With minor tweaks should work for your purposes.

like image 41
Javier C. H. Avatar answered Feb 26 '26 14:02

Javier C. H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!