Janaka Dombawela
Janaka Dombawela

Reputation: 1357

PHP call non-existing, undefined methods/functions

I have seen that there are some dynamic methods we can use in PHP frameworks that I guess which are actually does not exist, specially in frameworks like Laravel and Magento.

Ex:

MyClass::whereCity('london')->get();

What I want to do is call whereCity() method without actually defining it. Then capture the City part to filter results, so there might be lot of function calls such as whereId(), whereName(), whereCountry(), etc. Is it possible?

PS: Please note that I'm not looking for Magento or Laravel solution, those are mentioned for easy comprehension of the question. I want general solution that can be implemented with any PHP solution.

Upvotes: 0

Views: 1397

Answers (1)

borracciaBlu
borracciaBlu

Reputation: 4225

PHP has some Magic Methods that you can use to have dynamic methods.
In particular __call and __callStatic.

Eg from the documentation:

<?php
class MethodTest
{
    public function __call($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>


// Calling object method 'runTest' in object context
// Calling static method 'runTest' in static context

Please consider you still have to generate an algorithm to handle all the cases.

Upvotes: 3

Related Questions