When to use self over $this?

前端 未结 23 2813
醉梦人生
醉梦人生 2020-11-21 11:19

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

23条回答
  •  天涯浪人
    2020-11-21 12:03

    $this-> is used to refer to a specific instance of a class's variables (member variables) or methods.

    Example: 
    $derek = new Person();
    

    $derek is now a specific instance of Person. Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

    ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

    Static Variables Example: Pretend we have a database class with a single member variable: static $num_connections; Now, put this in the constructor:

    function __construct()
    {
        if(!isset $num_connections || $num_connections==null)
        {
            $num_connections=0;
        }
        else
        {
            $num_connections++;
        }
    }
    

    Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

    function __destruct()
    {
        $num_connections--;
    }
    

    Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

    echo DB::num_connections;
    

    Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).

    Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

    Static Method Example:

    public static function prettyName($first_name, $last_name)
    {
        echo ucfirst($first_name).' '.ucfirst($last_name);
    }
    
    echo Person::prettyName($derek->first_name, $derek->last_name);
    

    As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?

    1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
    2. Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!

    SELF:: If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number); If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

    The same goes for static variables: Example: View::templates_path versus self::templates_path

    Inside the DB class, if we were referring to a static method of some other object, we would use the object's name: Example: Session::getUsersOnline();

    But if the DB class wanted to refer to its own static variable, it would just say self: Example: self::connection;

    Hope that helps clear things up :)

提交回复
热议问题