Parent :: in class instances

I was wondering why there is no syntax in php $parent->function();, but instead we can use parent::function();one that looks like it is used in a static class. Am I missing some basics of php oop?

+3
source share
3 answers

I admit that this seems strange - and you missed nothing in the manual ^^

But:

  • Usually, when a child class overrides a method already defined in the parent class, you want the child method to completely override the parent
    • except __construct, I admit that this is probably why he explicitly said in the manual that you must call the parent method yourself __construct.
  • , $this , ; , .
  • parent:: ,


, parent::, :

class Father {
    public function method() {
        var_dump($this->a);
    }
}

class Son extends Father {
    protected $a;
    public function method() {
        $this->a = 10;
        parent::method();
    }
}

$obj = new Son();
$obj->method();


:

$ /usr/local/php-5.3/bin/php temp.php
int(10)

, $this , .

+2

, parent - , $parent , $child, , $child $parent.

, , class dog extends animal OOP !:)

+2

$parent , .

, , , , .

PHP , ( ), , . $this , , .

To create $parent, you will need to place the object inside $parent. You are not technically created a parent class, so it cannot be assigned to a variable.

BTW parent::function();has access to everyone $this.

Hence it works

class Test
{
    public function test()
    {
        echo $this->testing_var;
    }
}

class OtherTest
{
    public function run()
    {
        $this->testing_var = "hi";
        Test::test(); // echos hi
    }
}

And it will be a mistake if it is used outside the class and tells you that it should be declared static.

Test::test();
+1
source

Source: https://habr.com/ru/post/1727973/


All Articles