如何在 PHP 中的类中获取初始值设定项变量的名称 [英] How to get name of a initializer variable inside a class in PHP

查看:34
本文介绍了如何在 PHP 中的类中获取初始值设定项变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,是否可以在 PHP 中(使用或不使用反射)在此示例中的类方法中获取变量名称 abc.

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
   }

}

现在,当我使用像

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

我想看到显示的变量名称foo",换句话说,当返回方法内容时,类必须知道变量名称.

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.

推荐答案

如果需要,我总是传入变量名

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";
    }

}

用法:

$myVar = new myclass("myVar");
$yourVar = new myclass("yourVar");

echo $myVar->sayHello();
echo $yourVar->sayHello();

这篇关于如何在 PHP 中的类中获取初始值设定项变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆