PHP dynamic name for object property

后端 未结 2 1282

Instead of using

$object->my_property

I want to do something like this

$object->\"my_\".$variable
相关标签:
2条回答
  • 2020-12-06 10:46

    Use curly brackets like so:

    $object->{'my_' . $variable}
    
    0 讨论(0)
  • 2020-12-06 11:02

    How about this:

    $object->{"my_$variable"};
    

    I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:

    $x = new StdClass();
    $x->s1 = 'def';
    
    echo $x->{'s' . print("abc\n")};
    // prints
    // abc
    // def
    

    ... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:

    $x = new StdClass();
    $x->s1 = 'def';
    
    $someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
    echo $x->$someWeirdPropertyName;
    

    As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )

    P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )

    0 讨论(0)
提交回复
热议问题