Skip to main content

How to Read a Property Whose Name Is in a Variable or Constant in PHP

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

In PHP, $object->$name reads the property whose name is stored in the variable $name. For a name kept in a constant, or a name that isn't a valid PHP name, such as a URL, put the expression in braces: $object->{PLAN_KEY} or $object->{'https://photos.example.org/plan'}.

Syntax​

Syntax
$<object>->$<variable>
$<object>->{<expression>}
PartWhat it does
$<object>The object to read from, such as one that json_decode returned.
$<variable>A variable whose value is the property's name.
{<expression>}Any expression whose value is the property's name, such as a constant or a quoted string.

The PHP manual explains that for an expression such as $foo->$bar, "the local scope will be examined for $bar and its value will be used as the name of the property of $foo." It adds: "Curly braces may also be used to clearly delimit the property name", which is most useful "when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML)."

The Example​

The example decodes a user from JSON with two keys: name, and a plan stored under the URL https://photos.example.org/plan. JSON keys can be any text, so json_decode gives the object a property whose name is a URL. The code reads name through a variable, and the plan through a constant and through a quoted string, both in braces. Then it reads the constant without braces.

Prerequisites​

  • PHP. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which keeps the URL https://photos.example.org/plan in a constant named PLAN_KEY, decodes a user with a name and a plan under that URL, then echoes the name through a variable, and the plan through the constant in braces and through the quoted URL in braces.

main.php
<?php

declare(strict_types=1);

// A property name that isn't a valid PHP name, such as a URL, kept in a constant.
const PLAN_KEY = 'https://photos.example.org/plan';

// json_decode turns a JSON object into an object whose properties are its keys.
$user = json_decode('{"name":"Ada","https://photos.example.org/plan":"pro"}');

$field = 'name';
echo $user->$field . "\n"; // the name is in a variable
echo $user->{PLAN_KEY} . "\n"; // the name is in a constant: put it in braces
echo $user->{'https://photos.example.org/plan'} . "\n"; // or write the name as a string in braces

const PLAN_KEY = ...; defines a constant: a name for a value that never changes.

Step 2: Run It​

Terminal
php main.php
Output
Ada
pro
pro

The command is the same in zsh, bash and PowerShell.

Step 3: Leave Out the Braces​

Replace main.php with a version that writes the constant straight after ->:

main.php
<?php

declare(strict_types=1);

const PLAN_KEY = 'https://photos.example.org/plan';

$user = json_decode('{"name":"Ada","https://photos.example.org/plan":"pro"}');

// Without braces, PHP reads a property named PLAN_KEY, not the constant's value.
echo $user->PLAN_KEY . "\n";
Terminal
php main.php
Output
PHP Warning: Undefined property: stdClass::$PLAN_KEY in /Users/Shared/you/main.php on line 10

Warning: Undefined property: stdClass::$PLAN_KEY in /Users/Shared/you/main.php on line 10

A zsh terminal where php main.php prints Ada, pro and pro; for the changed file it prints PHP Warning: Undefined property: stdClass::$PLAN_KEY on line 10, twice.

What Happened​

  • $user->$field read Ada. PHP looked up $field, found 'name', and read the property with that name.
  • $user->{PLAN_KEY} and $user->{'https://photos.example.org/plan'} both read pro. PHP worked out the expression inside the braces first and used its value as the property's name.
  • Without the braces, $user->PLAN_KEY read a property named PLAN_KEY, which the object doesn't have. PHP warned Undefined property: stdClass::$PLAN_KEY and gave null, which echo printed as an empty line.
  • The warning appears twice because this PHP's settings both log errors to the terminal, as PHP Warning:, and display them, as Warning:.

Common Mistakes​

MistakeWhat happensDo this instead
Writing a constant straight after ->, as in $user->PLAN_KEYPHP reads a property named PLAN_KEY and warns Undefined property: stdClass::$PLAN_KEYWrite $user->{PLAN_KEY}
Writing a URL straight after ->, as in $user->https://photos.example.org/planParse error: syntax error, unexpected token ":", expecting "," or ";"Quote it in braces: $user->{'https://photos.example.org/plan'}
Reading a property that may be missingWarning: Undefined property and nullAdd a fallback with ??: $user->{PLAN_KEY} ?? 'free' gave free for a user without a plan

Troubleshooting​

SymptomLikely causeFix
Warning: Undefined property: stdClass::$PLAN_KEYA constant's name was used as the property namePut the constant in braces
Parse error: syntax error, unexpected token ":", expecting "," or ";"A URL written straight after ->Quote the URL in braces

FAQ​

Can I set a property this way too?​

Yes. For a user decoded from {"name":"Ada"}, $user->{PLAN_KEY} = 'team'; added the plan, and json_encode($user) printed {"name":"Ada","https:\/\/photos.example.org\/plan":"team"}. json_encode writes each / as \/ unless you pass JSON_UNESCAPED_SLASHES.

Does a URL in a variable need braces?​

No. With $field = 'https://photos.example.org/plan';, $user->$field read pro. Braces are for expressions, such as a constant or a quoted string, not for a plain variable.

What about associative arrays?​

An array key is already an expression, so a constant works without braces: $user[PLAN_KEY] read pro from ['https://photos.example.org/plan' => 'pro'].

Conclusion​

$object->$variable reads a property whose name is in a variable, and $object->{expression} reads one named by a constant or a quoted string, including names that aren't valid PHP names, such as URLs from json_decode. Without the braces, PHP takes the constant's name as the property's name.

Additional Resources​