Dynamic class method name in php

234

I'm working on a project using graphql-php. There is an example which suggests creating a class like this:

use Project\CategoryType;
use Project\PageType;

class Types {


private static $page;
private static $category;

    public static function page() {
        return self::$page ?: (self::$page = new PageType());
    }

    public static function category() {
        return self::$category ?: (self::$category = new CategoryType());
    }
}

Later I can use this class methods like so:

Types::page() orTypes::category()

This works fine. However, I think this is an anti-pattern and could be optimised. As the project grows, the number of similar functions and private class fields grows and this becomes inconvenient. Is there any way to refactor the class so I don't have to manually add a function for each type but still call the class methods as I do it now? (Types::page()).

464

Answer

Solution:

Please use __callStatic or __call magic methods. http://php.net/manual/en/language.oop5.overloading.php#object.callstatic

public static function __callStatic($name, $arguments)
{
    //$name is your type
}

People are also looking for solutions to the problem: php - Div not wrapping around all items in a loop

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.