Get a PHP object property that is a number
This should work:
$object->content->{'5'}
How to access object properties with names like integers or invalid property names?
Updated for PHP 7.2
PHP 7.2 introduced a behavioral change to converting numeric keys in object and array casts, which fixes this particular inconsistency and makes all the following examples behave as expected.
One less thing to be confused about!
Original answer (applies to versions earlier than 7.2.0)
PHP has its share of dark alleys that you really don't want to find yourself inside. Object properties with names that are numbers is one of them...
What they never told you
Fact #1: You cannot access properties with names that are not legal variable names easily
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->123foo; // error
Fact #2: You can access such properties with curly brace syntax
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!
Fact #3: But not if the property name is all digits!
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!
echo $o->{'123'}; // error!
Live example.
Fact #4: Well, unless the object didn't come from an array in the first place.
$a = array('123' => '123');
$o1 = (object)$a;
$o2 = new stdClass;
$o2->{'123'} = '123'; // setting property is OK
echo $o1->{'123'}; // error!
echo $o2->{'123'}; // works... WTF?
Live example.
Pretty intuitive, don't you agree?
What you can do
Option #1: do it manually
The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties:
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
$a = (array)$o;
echo $o->{'123'}; // error!
echo $a['123']; // OK!
Unfortunately, this does not work recursively. So in your case you 'd need to do something like:
$highlighting = (array)$myVar->highlighting;
$data = (array)$highlighting['448364']->Data;
$value = $data['0']; // at last!
Option #2: the nuclear option
An alternative approach would be to write a function that converts objects to arrays recursively:
function recursive_cast_to_array($o) {
$a = (array)$o;
foreach ($a as &$value) {
if (is_object($value)) {
$value = recursive_cast_to_array($value);
}
}
return $a;
}
$arr = recursive_cast_to_array($myVar);
$value = $arr['highlighting']['448364']['Data']['0'];
However, I 'm not convinced that this is a better option across the board because it will needlessly cast to arrays all of the properties that you are not interested in as well as those you are.
Option #3: playing it clever
An alternative of the previous option is to use the built-in JSON functions:
$arr = json_decode(json_encode($myVar), true);
$value = $arr['highlighting']['448364']['Data']['0'];
The JSON functions helpfully perform a recursive conversion to array without the need to define any external functions. However desirable this looks, it has the "nuke" disadvantage of option #2 and additionally the disadvantage that if there is any strings inside your object, those strings must be encoded in UTF-8 (this is a requirement of json_encode
).
What is the syntax for accessing PHP object properties?
$property1
// specific variable$this->property1
// specific attribute
The general use on classes is without "$"
otherwise you are calling a variable called $property1
that could take any value.
Example:
class X {
public $property1 = 'Value 1';
public $property2 = 'Value 2';
}
$property1 = 'property2'; //Name of attribute 2
$x_object = new X();
echo $x_object->property1; //Return 'Value 1'
echo $x_object->$property1; //Return 'Value 2'
Access object property which is a number
You convert multiple arrays to an object with the following code:
$obj1 = (object) ['name' => 'Jan', 'job' => 'IT'];
$obj2 = (object) ['name' => 'Adam', 'job' => 'PR'];
$obj3 = (object) ['name'=> 'Wojtek', 'job' => 'IT'];
$obj4 = (object) ['name' => 'Marcin', 'job' => 'Car'];
$obj = (object) [$obj1, $obj2, $obj3, $obj4];
To get the name
of the first object you can cast the object to an array (solution for PHP < 7.2):
echo ((array) $obj)[0]->name; // Jan
echo ((array) $obj)[1]->name; // Adam
Since PHP 7.2 you can also access numeric property names too:
echo $obj->{0}->name; // Jan
echo $obj->{1}->name; // Adam
complete example (with demo):
$obj1 = (object) ['name' => 'Jan', 'job' => 'IT'];
$obj2 = (object) ['name' => 'Adam', 'job' => 'PR'];
$obj3 = (object) ['name'=> 'Wojtek', 'job' => 'IT'];
$obj4 = (object) ['name' => 'Marcin', 'job' => 'Car'];
$obj = (object) [$obj1, $obj2, $obj3, $obj4];
//your output
var_dump($obj);
//PHP < 7.2: get the output of the name of the first object.
echo 'Test: '.((array) $obj)[0]->name; // Jan
//or since PHP 7.2
echo $obj->{0}->name; // Jan
demo: https://3v4l.org/kIVuS
How can I access an object property named as a variable in php?
Since the name of your property is the string '$t'
, you can access it like this:
echo $object->{'$t'};
Alternatively, you can put the name of the property in a variable and use it like this:
$property_name = '$t';
echo $object->$property_name;
You can see both of these in action on repl.it: https://repl.it/@jrunning/SpiritedTroubledWorkspace
How to create an object with number properties?
Er... Yes, you can. It's the very same syntax you are already using:
$obj = (object)nuLL;
$obj->{1} = 'Hi!';
var_dump($obj);
(Demo)
How can I access an object attribute that starts with a number?
What about this :
$Beeblebrox->{'2ndhead'}
Actually, you can do this for pretty much any kind of variable -- even for ones that are not class properties.
For example, you could think about a variable's name that contains spaces ; the following syntax will work :
${"My test var"} = 10;
echo ${"My test var"};
Even if, obviously, you would not be able to do anything like this :
$My test var = 10;
echo $My test var;
No idea how it's working internally, though... And after a bit of searching, I cannot find anything about this in the PHP manual.
Only thing I can find about {}
and variables is in here : Variable parsing -- but not quite related to the current subject...
But here's an article that shows a couple of other possiblities, and goes farther than the examples I posted here : PHP Variable Names: Curly Brace Madness
And here's another one that gives some additionnal informations about the way those are parsed : PHP grammar notes
PHP: Access Object Properties by String
Finally I have working code.
With mental support from @NigelRen
Emotional support from @FunkFortyNiner
And most of the code from this question about arrays
Test Object:
$obj = json_decode('{"snow":{"elevation":"365.4","results":"6","status":1},"wind":{"elevation":"365.4","windi":"100 mph","windii":"110 mph","windiii":"115 mph","status":1}}');
Test Directory:
$path = 'wind:windii';
Getter:
function get($path, $obj) {
$path = explode(':', $path);
$temp =& $obj;
foreach($path as $key) {
$temp =& $temp->{$key};
}
return $temp;
}
var_dump(get($path, $obj)); //dump to see the result
Setter:
function set($path, &$obj, $value=null) {
$path = explode(':', $path);
$temp =& $obj;
foreach($path as $key) {
$temp =& $temp->{$key};
}
$temp = $value;
}
//Tested with:
set($path, $obj, '111');
PHP Access Object Property with @ at the rate symbol
Wrap it into {}
:
$ABC->{"@total"}; // here it needs to insert quotes as well
Also note that you have to prefix your class object with the dollar sign, this is the link to sandbox example.
How can I acces the N'th object property name?
Cast your object to an array first:
$key = array_keys((array)$obj)[$i];
Related Topics
How to Integrate Nodejs + Socket.Io and PHP
Traits in PHP - Any Real World Examples/Best Practices
PHP Regex to Check Date Is in Yyyy-Mm-Dd Format
Checking If Array Is Multidimensional or Not
How to Install the Ext-Curl Extension with PHP 7
How to Easily Consume a Web Service from PHP
PHP Objects VS Arrays -- Performance Comparison While Iterating
PHP Technique to Query the Apns Feedback Server
How to Scrape Website Content in PHP from a Website That Requires a Cookie Login
Sharing Session Variables Between Multiple Subdomains