Best practices for static constructors

后端 未结 8 2408
无人及你
无人及你 2020-12-13 14:41

I want to create an instance of a class and call a method on that instance, in a single line of code.

PHP won\'t allow calling a method on a regular constructor:

相关标签:
8条回答
  • 2020-12-13 15:12

    A bit late to the party but I think this might help.

    class MyClass 
    {
    
        function __construct() {
           // constructor initializations here
        }
    
        public static myMethod($set = null) {
    
           // if myclass is not instantiated
           if (is_null($set)) {
               // return new instance
               $d = new MyClass();
               return $d->Up('s');
           } else {
               // myclass is instantiated
               // my method code goes here
           }
        }
    }
    

    this can then be used as

    $result = MyClass::myMethod();
    

    optional parameters can be passed through either the __constructor or myMethod.
    This is my first post and I hope I got the gimmicks right

    0 讨论(0)
  • 2020-12-13 15:13

    If you don't need a reference to the newly constructed Foo, why don't you simply make set_sth a static function (and have it create a new Foo internally if required)?

    If you do need to get hold of the reference, how would you do it? return $this in set_sth? But then set_sth can be made into a factory function anyway.

    The only situation I can think of is if you want to call chainable methods (like in a fluent interface) on a newly constructed instance all in one expression. Is that what you are trying to do?

    Anyway, you can use a general-purpose factory function for all types of objects, e.g.

    function create_new($type) {
        return new $type;
    }
    
    create_new('Foo')->set_sth();
    
    0 讨论(0)
提交回复
热议问题