开发者

have a variable in the value of a class property?

in my clas开发者_JAVA技巧s i have some properties. i want some values of these to have another property. but i noticed it wasnt possible.

code:

$property = "my name is: $this->name";

generated an error.

i set the $this->name with the constructor.

could you somehow accomplish this? i would like the "my name is: " to be defined in the property and not in the constructor if its possible.

thanks.


You could do something with variable variables:

$property = 'name';

echo "my name is: {$$property}";

In this case, $property evaluates to 'name' and $ is prepended, so $name is the result. This approach can have dangers as I hope you can appreciate.

I would question what you are trying to do here. If you want to template messages, consider something like this:

$template = 'hi my name is %name%';
echo str_replace('%name%', $name, $template);

More generally, use object properties as the language is designed and add methods to produce output strings if necessary. Variable variables are generally unnecessary.


All you should need to do is add brackets.

$property = "my name is: {$this->name}";

Although it also depends on what error it's giving. Does it say the error is occurring on this specific line?


You have to use $this->variable to access an object's own variable.

$this->property = "my name is: " . $this->name;

This only works inside the object itself. You can find more informations about this here: http://ch2.php.net/manual/en/language.oop5.visibility.php.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜