3

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();
Community
  • 1
  • 1
Vivek Aasaithambi
  • 919
  • 11
  • 23
  • Share your exact scenario please. do you want to override "a super class method" or just "a defined function"? and take a look at this: [link](http://stackoverflow.com/questions/2994758/what-is-function-overloading-and-overriding-in-php) – Babak Feb 26 '15 at 05:00
  • possible duplicate of [Dynamically create PHP class functions](http://stackoverflow.com/questions/12868066/dynamically-create-php-class-functions) – Babak Feb 26 '15 at 11:33

3 Answers3

5

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

VIVEK-MDU
  • 2,483
  • 3
  • 36
  • 63
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
3

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.

Javier C. H.
  • 2,124
  • 2
  • 19
  • 30
1

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
Babak
  • 419
  • 2
  • 16