Search code examples
phparraysclasstypesreturn

PHP: return an array from a class constructor


I just want to ask if it is possible to construct a class in PHP that returns an array when print_red

For example:

    <?php
    $c = new class(1,2,3){
        function __construct($var1, $var2, $var3){
            $this->value = [$var1 => [$var2, $var3]];
        }
    };

    print_r((array) $c);

i want it to result in:

Array ( [1] => Array ( [0] => 2 [1] => 3 ) )

instead i get

Array ( [value] => Array ( [1] => Array ( [0] => 2 [1] => 3 ) ) )


Solution

  • You need to use the following code instead:

    $c = new class(1,2,3){
        function __construct($var1, $var2, $var3){
            $this->$var1 = [$var2, $var3];
        }
    };
    
    print_r((array) $c);
    

    This will provide the expected output.

    Output:

    Array ( [1] => Array ( [0] => 2 [1] => 3 ) )

    Or you can try this:

    $c = new class(1,2,3){
        function __construct($var1, $var2, $var3){
            $this->value = [$var1 => [$var2, $var3]];
        }
    };
    
    print_r((array) $c->value);
    

    This will provide the same output:

    Array ( [1] => Array ( [0] => 2 [1] => 3 ) )