How to get name of a initializer variable inside a

2019-08-26 06:39发布

This question already has an answer here:

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.

标签: php oop
1条回答
淡お忘
2楼-- · 2019-08-26 07:17

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();
查看更多
登录 后发表回答