Static and Non-Static Calling in PHP

前端 未结 3 1033
不思量自难忘°
不思量自难忘° 2021-02-07 14:19

ok I have this code, that I\'m studying

 class scope{

    function printme(){
        return \"hello\";
    }

    public static function printme(){
        ret         


        
相关标签:
3条回答
  • 2021-02-07 14:21

    As non-static function has a lot of operations on it, I also need to call it as a static function so that I will not need to instantiate the class. Is this possible? or I really needed to rewrite the function to another function or class?

    If you need it static, then make it static. If you need it not, then keep it the way it is. It is possible from within non-static function to call static function.

    class Foo
    {
        public function bar()
        {
            Foo::zex();
    
            // or self::zex() or even $this->zex();
        }
    
        public static function zex()
        {
        }
    }
    
    
    $foo    = new Foo;
    $foo->bar();
    

    Ant the other way around.

    class Foo
    {
        public function bar()
        {
    
        }
    
        public static function zex()
        {
            $foo    = new Foo;
            $foo->bar();
        }
    }
    

    When you should do it or should you do it at all is another question. The most common use of the latter is probably the Singleton pattern.

    0 讨论(0)
  • 2021-02-07 14:22

    Here is the rule:

    A static method can be used in both static method and non-static method.

    A non-static method can only be used in a non-static method.

    0 讨论(0)
  • 2021-02-07 14:37

    If the instance of your class is rarely needed, you can have the static method create an instance, call the non-static method and return the value.

    class Scope {
        public function mynonstatic() {
        }
    
        public static function mystatic() {
            $s = new Scope();
            return $s->mynonstatic();
        }
    }
    

    Remember that a static method is really just a global function with reduced scope. They are useful, but are should not be created without good reason.

    0 讨论(0)
提交回复
热议问题