dsjswclzh40259075 2017-07-14 17:55
浏览 32
已采纳

PHP静态方法与非静态方法/标准函数

I am working on a web app and writing pure OOP based PHP for the first time. And I have a question about static method VS standard function:

Here is an example scenario:

class Session
{
    public function start_new_session()
    {
        session_start();
        //other code here like token generator
    }
}

VS

class Session
{
    static function start_new_session()
    {
        session_start();
        //other code here like token generator
    }
}

Questions

  1. What is the difference in both?
  2. Which is better for my case?
  3. Any application? (I mean, what are the best scenario to use static method and standard function)

My Research:

I spent some time to find the answer but don't found relevant answer however I found a lot of debate and useful material. Believe me it is super hard to decide (Who is right/wrong?) for a beginner like me:

  1. In this question Someone said, It's horrible idea to use cookies in static functions and someone's saying It's a great idea

  2. And in this question: Everyone is debating on performance and some experts are saying, the static functions execute faster and some saying; functions are faster. And result also vary because of different versions of php.

Some useful stat:

PHP 5.2 : static methods are ~10-15% faster.

PHP 5.3 : non-static methods are ~15% faster

PHP 5.4 : static methods are ~10-15% faster

PHP 5.5 : static methods are ~20% faster

  • 写回答

1条回答 默认 最新

  • duande1146 2017-07-14 20:28
    关注

    To call a non-static method you need to instantiate the class (use the new keyword to create a new instance of the class).

    When calling a static method you don't have to "new it up" but it won't have direct access to any of the non-static properties or methods. There are dozens of use-cases / scenarios where you might want to use one over the other.

    To be quite honest it has never even crossed my mind to think about performance of using one over the other. If it got to a point where it made that much of a noticeable difference (and all major steps had been taken to increase efficiency) then I would imagine that either the maintenance costs of such a big application would outweigh the need for the increased efficiency or the logic behind the app is fairly flawed to begin with.


    Examples for static and non-static

    If I was going to use a class for the example in your question then I would use the static version as nothing in the method is reliant on other properties of the class and you then don't have to instantiate it:

    Session::start_new_session()
    

    vs

    $session = new Session();
    
    $session->start_new_session();
    

    Also, static properties on a class will remember state that would have otherwise been lost if you were to use a non-static property and instantiation:

    class Session
    {
        protected static $sessionStarted = false;
    
        static function start_new_session()
        {
            if (!static::$sessionStarted) {
                session_start();
                static::$sessionStarted = true;
            }
        }
    }
    

    Then even if you did:

    $session = new Session();
    
    $hasStated = $session::sessionStarted;
    

    $hasStarted would still be true.

    You could even do something like:

    class Session
    {
        protected static $sessionStarted = false;
    
        public function __construct()
        {
            $this->startIfNotStarted();
        }
    
        function startIfNotStarted()
        {
            if (!static::$sessionStarted) {
    
                session_start();
    
                static::$sessionStarted = true;
            }
        }
    }
    

    This way you don't need to worry about starting the session yourself as it will be started when you instantiate the class and it will only happen once.

    This approach wouldn't be suitable if you had something like a Person class though as the data would be different each time and you wouldn't want to use the same data in difference instantiations.

    class Person
    {
        protected $firstname;
    
        protected $lastname;
    
        public function __construct($firstname, $lastname)
        {
            $this->firstname = $firstname;
            $this->lastname = $lastname;
        }
    
        public function getFullname()
        {
            return "{$this->firstname} {$this->lastname}";
        }
    }
    

    //

    $person1 = new Person('John', 'Smith');
    $person2 = new Person('Jane', 'Foster');
    
    $person1->fullname(); // John Smith
    $person2->fullname(); // Jane Smith
    

    If you were to use static methods / properties for this class then you could only ever have one person

    class Person
    {
        protected static $firstname;
    
        protected static $lastname;
    
        static function setName($firstname, $lastname)
        {
            static::$firstname = $firstname;
            static::$lastname = $lastname;
        }
    
        static function getFullname()
        {
            return static::$firstname . ' ' . static::$lastname;
        }
    }
    

    //

    Person::setName('John', 'Smith');
    Person::setName('Jane', 'Foster');
    
    Person::getFullname(); //Jane Foster
    

    The debates

    You are probably going to see a lot of debates over which is better and wha the best practices are when it comes to PHP (not just about static and not-static methods).

    I wouldn't get bogged down with it though! If you find that one side makes more sense to you (and whatever you building at the time) then go with that one. Standards and opinions change all the time in this community and half of the stuff that was a problem 5 years ago (or even less) will actually be non-issues today.

    Take the Laravel framework as an example -- one of the (many) debates is that Facades are bad because they're static and make use of magic methods which is hard to test and debug. Facades are actually very easy to test and with the use of stack trace error reporting it isn't hard to debug at all.

    That being said, if you find the majority of people are saying the same thing and there isn't really a debate for the other side, there is probably a reason e.g. don't use mysql_ functions or don't run queries inside a loops.

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?