简体   繁体   中英

Dynamic class method name in php

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() or Types::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() ).

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM