0

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.

3
  • This is a bad idea. It violates abstraction. Why do you want to do this? Commented Jun 25, 2016 at 0:00
  • because i don't want to heavy my class functions and some data want to call from outside the function Commented Jun 25, 2016 at 0:32
  • @ShiraNai7 answer solved my problem Commented Jun 25, 2016 at 0:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You very much this solved my biggest problem that is it what i wanted
0

Inside your function, you can make a check:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.