Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property value as string literal in PHP

Okay, im relearning php for a small home project and run into a problem so heres a quick one for all u php experts:

I have build an abstract class which should access properties of YQL Yahoo returned JSON objects decoded to PHP objects. Lets say I want to access the property id then I do like this right:

print($phpObject->id);  // Okay

But I want to be able to access the property in a more abstract manner, ie something like this:

$propertyName = 'id';
print($phpObject[$propertyName]); 
print($phpObject["id"]);    

But none of the above is working - I am sure for obvious reasons, but me not beeing PHP expert I am having a hard time figurring out this call. Please help me here.

like image 844
Muleskinner Avatar asked Jan 06 '11 22:01

Muleskinner


People also ask

How do you access the properties of an object in PHP?

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .

What is access string in PHP with example?

The simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks ('), like this: Example: $my_string = 'Hello World'; You can also use double quotation marks (“). However, single and double quotation marks work in different ways.

What is a PHP literal?

PHP string literal A string literal is the notation for representing a string value within the text of a computer program. In PHP, strings can be created with single quotes, double quotes or using the heredoc or the nowdoc syntax. literals.php. <?

How strings are declared in PHP explain string operators?

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in PHP. For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double backslash (\\).


1 Answers

$propertyName = 'id';

print($phpObject->{$propertyName});
like image 78
Diablo Avatar answered Oct 12 '22 15:10

Diablo