This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Objects in PHP Forum

View Course » View Exercise

418 points
Picture
Submitted by
Pjotr Leshkin
about 2 years ago

Why it's needed to use $this->xxx notation?

<?php
    class Dog {
        public $numLegs = 4;
        public $name;
       public function __construct($name){
        $this->name = $name;
        }
        public function bark(){
            return 'Woof!';
        }
        public function greet(){
            return 'Hello, my darling ' .$this->name . ' ' ; 

        }

    };
      $dog1 = new Dog($name = 'Barker');
    $dog2 = new Dog ($name = "Amigo") ;
    echo $dog1->greet();?>

for example code upside will not work, if in "greet" method you will use "$name" instead of
"$this->name ".
I am wondering, what is the reason for using such weird notation.On my mind it would be much more user-friendly to use first option. Perhaps, there is something going on beneath the code. Can someone try to explain me or give a link onto resource where this "this->" -concept is explained?
Beforehand, TY.


1 vote

permalink

This is copied from lesson 5:
"Finally, the weird way to assign the values: $this->prop1 = $prop1 means that the value you pass in the __construct() function via the new keyword is assigned to $this, which represents the object you are dealing with, and ->prop1 is the actual property of the object."

My explanation:
Basically, it just means that the $this-> means: "Get the following property from $this". The prop1 means that prop1 is the property to get from $this. The = $prop1 means: "Assign that value to the variable $prop1". Also, boring12345 said, "The weird way to assign the values", indicating that he doesn't know why they did it that way either.
Hope this helped!

401 points
5361354f9c4e9d42bf000979_559338498
Submitted by
programmer.exe
about 2 years ago