-1

I was messing around and discovered that you could actually call static methods with $this->method()

And it got me a bit confused and curious about the differences between the 3 ways (that I know of) to call static methods

$this->method();
static::method();
self::method();

Now, I think I understand the difference between the latter two, but what about the first one?

TKoL
  • 13,158
  • 3
  • 39
  • 73

2 Answers2

0

It is important to understand the behavior of static properties in the context of class inheritance:

Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.

Static properties defined ONLY in the parent class will share a COMMON value.

declare(strict_types=1);

class staticparent {
    static    $parent_only;
    static    $both_distinct;

    function __construct() {
        static::$parent_only = 'fromparent';
        static::$both_distinct = 'fromparent';
    }
}

class staticchild extends staticparent {
    static    $child_only;
    static    $both_distinct;

    function __construct() {
        static::$parent_only = 'fromchild';
        static::$both_distinct = 'fromchild';
        static::$child_only = 'fromchild';
    }
}

$a = new staticparent;
$a = new staticchild;

More on https://www.php.net/manual/en/language.oop5.static.php

0

self using for static method and variable in class

$this using for non static method and variable

static generally using call child class of static methods or variable For example late static

For example late static binding

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28