-3

I just want clarity of $this behaviour in PHP. From below program I want to know how can refer $this in class B to class A members, also on same time how can I use $this to refer the class B scope.

 <?php //php 7.0.8

  class A{ 
     public $name="test"; 
     public function func1(){
       echo $this->name="classAFunc";
    }
  }
 class B extends  A {
    public $name="classB";
    public function func2(){
      echo $this->name ;
   }   
 }

   $test = new B();
   echo $test->name; // classB
   echo $test->func1();//classAFunc
   echo $test->func2();//classAFunc //I want this should output classB

?>

If I am going somewhere wrong please point it out. you refer here to play around : run this program

Mohammed
  • 9
  • 3
  • please check [this](https://en.wikipedia.org/wiki/This_(computer_programming)) . `$this` is used to access the members(properties and methods) of the object of the current class (the class that you write the code in it's scope) – Accountant م Dec 16 '18 at 10:03
  • echo $this->name=“ClassAFunc”; is not valid syntax, perhaps use Google prior to asking questions – Jaquarh Dec 16 '18 at 10:28
  • Possible duplicate of [Reference — What does this symbol mean in PHP?](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Mike Doe Dec 16 '18 at 11:44

2 Answers2

1

//classAFunc //I want this should output classB

$this has nothing to do with achieving what you want, because function func1 in your program changes the name property from "classB" to "classAFunc", this is what you did here

echo $test->name; // classB
echo $test->func1();//classAFunc (func1 sets the name property to classAFunc)
echo $test->func2();//classAFunc //name property of the object is already changed by func1

you can call func2() before func1() to get what you want

or you can make func2() sets the name property, like this

public function func2(){
    echo $this->name = "classB";
} 

Note: when B extended A their name property are merged, meaning the objects of B will have only 1 name property not 2!

Accountant م
  • 6,975
  • 3
  • 41
  • 61
0

Change access modifier of $name variable to private. ie; public $name="test"; to private $name="test"; of class A

adhi
  • 1
  • 1
  • Can you explain this why such thing need to do ? cant we solve this problem using constructor or super class concept @adhi – Mohammed Dec 16 '18 at 10:03
  • Altough, this is not a correct solution please explain your answer. You can't just simply sya: do it like this and not give an explaination. – Fjarlaegur Dec 16 '18 at 10:08