2

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

2
  • print_r() is a function used for debug. It shouldn't matter how its output looks like. Why is it that important to you? I suspect you are trying to solve a different problem. Commented Oct 30, 2017 at 9:06
  • I am actually trying to get an array of a class that must be the exact style like mentioned above and simply used print_r to explain the result Commented Oct 30, 2017 at 9:10

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting approach to use $this->${variable name} as value. Is there a documentation to $this->${variable name} somewhere?
@thebigsmileXD Yes, these are called Variable Variables
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.