user12699088
user12699088

Reputation:

how to echo something if called method doesnt exists in class

Im trying to echo "sorry i dont know what to do" if we call a method that doesnt exist in my class (named Pony)

Here is my Class :

<?php

class Pony{
    public $_name;
    public $_gender;
    public $_color;

    public function __construct($name,$gender,$color)
    {
          $this->_name=$name;
          $this->_gender=$gender;
          $this->_color=$color;
    }


    public function speak(){
        echo "Hiii hiii hiiii<br>";
    }
    public function __destruct()
    {
        echo "I'm a dead pony.<br>";
    }

    public function __toString()
    {
        return "Don't worry, im a pony ! <br>";
    }
}

but when i try to write my "if statement" inside my class, the method_exists function just doesnt take the name of my class in parameter..

Thanks in Advance !

Upvotes: 1

Views: 155

Answers (1)

u_mulder
u_mulder

Reputation: 54841

When calling non_existing method of class, method __call is invoked:

class Pony{
    public $_name;
    public $_gender;
    public $_color;

    public function __construct($name,$gender,$color)
    {
          $this->_name=$name;
          $this->_gender=$gender;
          $this->_color=$color;
    }


    public function speak(){
        echo "Hiii hiii hiiii<br>";
    }
    public function __destruct()
    {
        echo "I'm a dead pony.<br>";
    }

    public function __toString()
    {
        return "Don't worry, im a pony ! <br>";
    }

    public function __call($methodName, $arguments)
    {
        return "im a pony, i don't know what to do with {$methodName}! <br>";
    }

}

$p = new Pony('', '', '');
echo $p->swim();

Fiddle here.

Upvotes: 1

Related Questions