开发者

how to store constructed variable name

开发者 https://www.devze.com 2023-04-12 19:25 出处:网络
I wold like to get the following variable name: class ClassA { public $my_name_is = \"\"; function __construct($tag,$cont = null)

I wold like to get the following variable name:

class ClassA
{
    public $my_name_is = "";
    function __construct($tag,$cont = null)
    {
        $this->my_name_is = ???开发者_运维知识库;
    }
}
$OBJ = new ClassA();
echo($OBJ->my_name_is);

This should output

OBJ

Is it possible?

I make tag HTML generator and the id of the tag should be the object name so I must not write it twice:

$input_pwd = new tag("td>input TYPE=PASSWORD.box_lg#input_pwd"); //old way
$input_pwd = new tag("td>input TYPE=PASSWORD.box_lg"); //upgraded way

should generate:

<td><input TYPE=PASSWORD ID='input_pwd' CLASS='box_lg'></td>


No, it's not. An object doesn't know the names of variables that refer to it.

"Needing" this is usually a design flaw.


You can use the magic constant __CLASS__ for retrieving the name of the current class, but there is no way for a class to get the name of the variable which stores the class. You may want to extend your class and still use __CLASS__:

class OBJ extends ClassA {
    public function getName() {
        return __CLASS__;
    }
}
$OBJ = new OBJ();
$OBJ->getName();

See also: http://php.net/manual/en/language.constants.predefined.php


If you simply want to ensure that each reference to the object has a unique ID, you can do that with a static variable.

class ClassA {
    public function getUniqueName() {
        static $count = 0;
        ++$count;
        return __CLASS__ . '.' . $count;
    }
}
$OBJ = new ClassA();
echo($OBJ->getUniqueName();

Every time that method is called, it will give you a different result. If you call it only once on each variable, you should be fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号