When to use self over $this?

前端 未结 23 2827
醉梦人生
醉梦人生 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 11:58

    According to php.net there are three special keywords in this context: self, parent and static. They are used to access properties or methods from inside the class definition.

    $this, on the other hand, is used to call an instance and methods of any class as long as that class is accessible.

    0 讨论(0)
  • 2020-11-21 11:59

    I ran into the same question and the simple answer is:

    • $this requires an instance of the class
    • self:: doesn't

    Whenever you are using static methods or static attributes and want to call them without having an object of the class instantiated you need to use self: to call them, because $this always requires on object to be created.

    0 讨论(0)
  • 2020-11-21 12:00

    self refers current class(in which it is called),

    $this refers current object. You can use static instead of self. See the example:

        class ParentClass {
                function test() {
                        self::which();  // output 'parent'
                        $this->which(); // output 'child'
                }
    
                function which() {
                        echo 'parent';
                }
        }
    
        class ChildClass extends ParentClass {
                function which() {
                        echo 'child';
                }
        }
    
        $obj = new ChildClass();
        $obj->test();
    

    Output: parent child

    0 讨论(0)
  • 2020-11-21 12:02

    Use self if you want to call a method of a class without creating an object/instance of that class, thus saving RAM (sometimes use self for that purpose). In other words, it is actually calling a method statically. Use this for object perspective.

    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-11-21 12:03

    Inside a class definition, $this refers to the current object, while self refers to the current class.

    It is necessary to refer to a class element using self, and refer to an object element using $this.

    self::STAT // refer to a constant value
    self::$stat // static variable
    $this->stat // refer to an object variable  
    
    0 讨论(0)
提交回复
热议问题