2

I want to be able to set an attribute of an object but the attribute name would be generated. How can I accomplish this in PHP, without using eval()

e.g.:

$obj->name = "Prakash Raman"; // Works
$obj->$attr_name = <some value>; // Would want something like this to work

I would like to be able to change $attr_name.

Thanks.

3 Answers 3

8
$obj->{$attr_name} = "New value";

This will accomplish exactly that.

A word of caution though, I would reccomend using it in conjunction with property_exists() to verify the existence of the property.

Sign up to request clarification or add additional context in comments.

Comments

1

I understand the question has a valid answer, but just to add onto the many ways you can do this:

<?php
$myClass = new ReflectionClass($someClass);
if($myClass->hasProperty($someProperty)){
   $myClass->getProperty($someProperty)->setValue($someClass,__NEW__VALUE__);
}
?>

Comments

1

Funnily enough, your code as posted will work. (++ for property_exists, though.)

http://codepad.org/qW0Tj4MR

Comments

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.