ghabriel
ghabriel

Reputation: 123

PHP - How to know where magic method __call() get called from

Basically, magic method __call() will be called if there is no method exists inside class - CMIIW.

For example I have base Controller like this

class Controller
{
    public function __call($method, $args)
    {
        //echo error       
    }

    public function foo()
    {
        echo "foo";
    }
}

and AuthController which extends base Controller like this

class AuthController extends Controller
{
    public function create()
    {
        return $this->bar();
    }
}

My question is how did I know where is it called from? It's for debugging purposes. All I know is magic constant __LINE__

Upvotes: 0

Views: 93

Answers (1)

cn0047
cn0047

Reputation: 17091

Maybe you're looking to function get_called_class, like this:

public function __call($method, $args)
{
    var_dump(get_called_class());
}

Will return: string(14) "AuthController"

Full code looks like this:

<?php

namespace Foo;

class Controller
{
    public function __call($method, $args)
    {
        var_dump(get_called_class());
    }

    public function foo()
    {
        echo "foo";
    }
}

namespace Bar;

class AuthController extends \Foo\Controller
{
    public function create()
    {
        return $this->bar();
    }
}

$c = new \Bar\AuthController();
$c->create();

Please check it out here.

Upvotes: 1

Related Questions