문제

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!

도움이 되었습니까?

해결책

<?php 
class ClassFoo {
    const MY_CONSTANT = "bar";

    function __construct() {
        $this->{ClassFoo::MY_CONSTANT} = "foo";
    }
}

$a = new ClassFoo();
var_dump($a);

다른 팁

You can use the constant in a variable and use that variable as property name:

$propertyName = ClassFoo::MY_CONSTANT;
$this->$propertyName = 'foo';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top