Search code examples
phplaravellaravel-3

Need to call static attributes "dynamically" on PHP


I'm having the following issue.

Inside my Banner class I have:

public static $flag_status = array(
                               'Unpublished'
                          ,    'Published'
                          );

Out of the Banner class, I have an array that contains the 'flag_status' value which represents the attribute on the Banner class.

Let's suppose that I'm getting this value from the array and storing on a variable like this:

$name_attr = 'flag_status';

I need to call:

Banner::$name_attr; 

And it should return the same as calling:

Banner::$flag_status;

Is it possible to do?


Solution

  • Use two dollar signs:

    Banner::$$name_attr;
    

    Example:

    class Foo {
        public static $flag_status = array( 'foo', 'bar' );
    }
    
    $name_attr = 'flag_status';
    
    print_r(Foo::$$name_attr);
    

    Produces:

    Array
    (
        [0] => foo
        [1] => bar
    )