<?php
class ClassFoo {
const MY_CONSTANT = "bar";
function __construct() {
$this->{ClassFoo::MY_CONSTANT} = "foo";
}
}
$a = new ClassFoo();
var_dump($a);
Variable variables named after constants
-
05-03-2022 - |
문제
I have the following class:
class ClassFoo {
const MY_CONSTANT = "bar";
function __construct() {
$my_object = new stdClass;
// This does not work
$my_object->$ClassFoo::MY_CONSTANT = "foo";
}
}
I am trying to create a variable of the object $my_object
to have a name equal to the constant I've defined (ClassFoo::MY_CONSTANT
).
The following does not work:
$my_object->$ClassFoo::MY_CONSTANT = "foo";
Nor does this:
$my_object->$constant("ClassFoo::MY_CONSTANT") = "foo";
There must be a simple solution to this but I can't seem to find it!
해결책
다른 팁
You can use the constant in a variable and use that variable as property name:
$propertyName = ClassFoo::MY_CONSTANT;
$this->$propertyName = 'foo';
제휴하지 않습니다 StackOverflow