0

I'm using this code to initialize a multi-dimensional array:

protected $availableAuthMechanisms = [
    'open' => (object)[
        'owner'       => 'Mohsin.Auth',
        'name'        => 'Open',
        'identifier'  => 'open'
    ]
];

And I get an error that says "Constant expression contains invalid operations". What is going on here?--how do I achieve this properly?

1 Answer 1

3

Unfortunately you cannot cast an array inside an array to an object when defining it.

What you could do is cast the array to an object once you retrieve it.

Example:

protected $availableAuthMechanisms = [
    'open' => [
        'owner'       => 'Mohsin.Auth',
        'name'        => 'Open',
        'identifier'  => 'open'
    ]
];

$obj = (object) $this->availableAuthMechanisms['open'];
Sign up to request clarification or add additional context in comments.

2 Comments

That's a shame. I thought I was messing something up as I saw an example in php.net where this was being used the way I did it in my question. >> php.net/manual/en/language.types.object.php#117149 Thanks for clearing it up.
@SaifurRahmanMohsin Ah yes, in that example the array is also casted to an object right after assigning it to a variable ;)

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.