musthafa
musthafa

Reputation: 433

Get a particular value of a variable from the function which is inside a class

I want access only a particular value from the function declared inside the class

class Animal
{
    var $name;

    function __Construct($names){
        $this->name=$names;
    }
}

class Dog extends Animal 
{
    function prop($ht, $wt, $ja)
    {
        $height=$ht;
        $weight=$wt;
        $jaw=$ja;
    }
}

$dog= new dog('Pug');
$dog->prop(70, 50, 60);

I want to echo only a particular value from the dog function prop.

something like dog->prop->jaw;

How is this done?

Upvotes: 0

Views: 51

Answers (1)

Phil
Phil

Reputation: 164834

Sounds like you want something like this...

class Dog extends Animal {
    private $props = array();

    public function prop($height, $width, $jaw) {
        $this->props = array(
            'height' => $height,
            'width'  => $width,
            'jaw'    => $jaw
        );
        return $this; // for a fluent interface
    }

    public function __get($name) {
        if (array_key_exists($name, $this->props)) {
            return $this->props[$name];
        }
        return null; // or throw an exception, whatever
    }
}

Then you can execute

echo $dog->prop(70, 50, 60)->jaw;

or separately

$dog->prop(70, 50, 60);
echo $dog->jaw;

Upvotes: 2

Related Questions