When to use self over $this?

2018-12-31 01:49发布

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

When is each appropriate?

标签: php class scope
22条回答
倾城一夜雪
2楼-- · 2018-12-31 02:27

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.

查看更多
梦醉为红颜
3楼-- · 2018-12-31 02:31

I believe question was not whether you can call the static member of the class by calling ClassName::staticMember. Question was what's the difference between using self::classmember and $this->classmember.

For e.g., both of the following examples work without any errors, whether you use self:: or $this->

class Person{
    private $name;
    private $address;

    public function __construct($new_name,$new_address){
        $this->name = $new_name;
        $this->address = $new_address;
    }
}

class Person{
    private $name;
    private $address;
    public function __construct($new_name,$new_address){
        self::$name = $new_name;
        self::$address = $new_address;
    }
}
查看更多
大哥的爱人
4楼-- · 2018-12-31 02:31

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.

查看更多
浅入江南
5楼-- · 2018-12-31 02:32

From this blog post:

  • self refers to the current class
  • self can be used to call static functions and reference static member variables
  • self can be used inside static functions
  • self can also turn off polymorphic behavior by bypassing the vtable
  • $this refers to the current object
  • $this can be used to call static functions
  • $this should not be used to call static member variables. Use self instead.
  • $this can not be used inside static functions
查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 02:32

As no one here talked about performances, here is a small benchmark I did (5.6):

 Name     | Time    | Percent  
----------|---------|---------  
 $this->  | 0.99163 | 106.23%  
 self::   | 0.96912 | 103.82%  
 static:: | 0.93348 | 100%

Those are the results for 2 000 000 runs, and here is the code I used:

<?php

require '../vendor/autoload.php';

// My small class to do benchmarks
// All it does is looping over every test x times and record the
//   time it takes using `microtime(true)`
// Then, the percentage is calculated, with 100% being the quickest
// Times are being rouned for outputting only, not to calculate the percentages
$b = new Tleb\Benchmark\Benchmark(2000000);

class Foo
{
    public function calling_this()
    {
        $this->called();
    }

    public function calling_self()
    {
        self::called();
    }

    public function calling_static()
    {
        static::called();
    }

    public static function called()
    {
    }
}

$b->add('$this->',  function () { $foo = new Foo; $foo->calling_this(); });
$b->add('self::',   function () { $foo = new Foo; $foo->calling_self(); });
$b->add('static::', function () { $foo = new Foo; $foo->calling_static(); });

$b->run();
查看更多
妖精总统
7楼-- · 2018-12-31 02:33

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

查看更多
登录 后发表回答