How to get name of a initializer variable inside a

2019-08-26 06:30发布

问题:

This question already has an answer here:

  • Get variable name of object inside the object php 3 answers

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.

回答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();


标签: php oop