Fahad Kazmi Fahad Kazmi - 5 months ago 12
PHP Question

PHP OOP print a variable which has value inside the function but call from outside to be print

Is it possible to print a variable which has the value inside the function but it's called from outside the function to be print in object oriented programming in PHP

Let's explain by example

My class looks like as:

class my {
public $a;

public function myFunc(){
$name = "fahad";
echo $this->a;
}

}


It should print the value of
$name
when the function is call, as I am trying:

$class = new my();
$class->a = '$name';
$class->myFunc();


But it did't work and print the result as:

$name


I want it should print the value of variable
$name
which is inside the function

How it can be possible?

Thank You.

Answer

You can use variable variables to do this, but it's usually considered bad practice.

class my {
   public $a;

   public function myFunc(){
       $name = "fahad";
       echo ${$this->a};
   }
}

$class = new my();
$class->a = 'name';
$class->myFunc();

Output:

fahad