0

I would like to know, if it is possible in PHP (using reflection or not) to get the variable name abc inside the class method in this example.

class Example { public function someMethod() { // once this method is called, I want it to echo `abc` in this example } } 

Now, when I call the method using a variable name like

$abc= (new Example)->someMethod(); echo $abc; // abc 

I would like to see the name of the variable, 'foo' shown, in other words the class would have to be aware of the variable name, when returning the methods contents.

19
  • 1
    You want the object to be aware of the name of the variable its assigned to? Commented Jan 8, 2015 at 22:54
  • And what do you expect to be echoed if you do $abc = (new Example)->someMethod(); $def = &$abc; echo $def; or even $abc = (new Example)->someMethod(); $def = &$abc; unset($abc); echo $def; Commented Jan 8, 2015 at 22:55
  • I don't think this is possible. What would it echo if it were $abc = array($example->someMethod())? Commented Jan 8, 2015 at 22:56
  • @Barmar It would echo abc Actually, it is as shown here just wanted to know if there was an easier way. Commented Jan 8, 2015 at 23:04
  • 2
    You say you want to see the variable name foo shown but there's no mention of foo before. So what exactly are you trying to achieve here? Can you give a use case? Commented Jan 8, 2015 at 23:08

1 Answer 1

1

I always pass in the name of the variable it will be assigned to if it it is required

class myclass { var $myname; function __construct($myname='no name') { $this->myname=$myname; #print "In BaseClass constructor\n"; } function sayHello() { return "hello from " . $this->myname . "\n"; } } 

usage:

$myVar = new myclass("myVar"); $yourVar = new myclass("yourVar"); echo $myVar->sayHello(); echo $yourVar->sayHello(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but this is just what a 1-level PHP developer would do. If you seen in my question, I am asking for possible answer involving Reflection if I wanted to pass it as argument, it would have been too easy.
I thought php was for 1-level programmers. I mean a square wheel will work but ...
@SoyF.Elmono Maybe. But you can't compare people who use only PHP as one could be expert and the other could be a beginner. I am neither, so this answer seemed to noob for me
Seems stackoverflow.com/questions/19135959/… - is how they do it too. Perhaps not so noob?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.