user1173169
user1173169

Reputation:

Within a class : Access to a function A from a function B

I have a problem which is probably not for most of you. Sorry if it is obvious for you...

This is my code :

class Bat
{
      public function test()
      {
        echo"ici";
        exit();
      }

      public function test2()
      {
        $this->test();
      }
}

In my controller:

bat::test2();

i have an error:

Exception information: Message: Method "test" does not exist and was not trapped in __call()

Upvotes: 0

Views: 64

Answers (1)

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28583

Bat::test2 refers to a static function. So you have to declare it static.

class Bat
{
      public static function test()
      {
        echo"ici";
        exit();
      }

      // You can call me from outside using 'Bar::test2()'
      public static function test2()
      {
        // Call the static function 'test' in our own class
        // $this is not defined as we are not in an instance context, but in a class context
        self::test();
      }
}

Bat::test2();

Else, you need an instance of Bat and call the function on that instance:

$myBat = new Bat();
$myBat->test2();

Upvotes: 1

Related Questions