Access object property with hyphen in PHP
Question:
How to access object property with hyphen in PHP? Answer:
$birthDate = $user->{'birth-date'};
Description:
Accessing data in a JSON object that was created by the json_decode
method using an API response can contain properties with illegal names. For example, in PHP the hyphen or dash -
is not allowed in variable names. If you try to access an object property with a hyphen in its name:
$birthDate = $user->birth-date;
you will get the following error:
Fatal error: Uncaught Error: Undefined constant "date"
To avoid this problem you can use the syntax with curly braces like this:
$birthDate = $user->{'birth-date'};
Reference:
PHP object properties reference
Share "How to access object property with hyphen in PHP?"
Related snippets:
Tags:
access, object, property, hyphen, dash, space, php Technical term:
Access object property with hyphen in PHP