Reputation: 1009
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.
Upvotes: 0
Views: 519
Reputation: 6560
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
Upvotes: 2
Reputation: 14921
Inside your function, you can make a check:
public function myFunc(){
if($this->a == '$name'){
$name = 'fahad';
echo $name;
}else echo $this->a;
}
Upvotes: 0