inxomnyaa
inxomnyaa

Reputation: 99

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 ) ) )

Upvotes: 2

Views: 2290

Answers (2)

inxomnyaa
inxomnyaa

Reputation: 99

This also works, but i consider @mega6382's answer as better

<?php
$c = new class(1,2,3) extends ArrayObject{
    function __construct(int $var1, int $var2, int $var3){
        parent::__construct([$var1 => [$var2, $var3]]);
    }
};

print_r((array) $c);

Gives:

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

Upvotes: 0

mega6382
mega6382

Reputation: 9396

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 ) )

Upvotes: 3

Related Questions