tags:

views:

40

answers:

3

Suppose, i have class,

define('property', 'test');

class myClass
{
public $test;
}

$obj=new myClass;

Can i use like this,

$obj->property="value";

Is there any way to achieve this?

+2  A: 

Yes:

$obj->{property}="value";
Artefacto
that would work i suppose :/ but why oh why would you want to, there constants for a reason, and they have global scope, so why would you need to?
RobertPitt
Love the way of answer. TO THE POINT.
Chetan sharma
@RobertPitt I can think of several cases. Suppose you have a class with two properties `$name` and `$nameutf8`. Which one is filled depends on whether the content is encoded in UTF-8 or not. Depending on which data the script handles, you can change the constant, e.g at first you do not support UTF-8 and want to make the migration easier.
Artefacto
@Artefacto I dont know. The example smells. You are effectively littering all property names of classes requiring such a switch as constants into the global scope then. Wouldn't it be better to just pass the constant to a setter, like `setName('foo', CHARSET);` and handle what gets filled internally. Or simply pass the constant into the constructor so the class knows it has to fill the UTF8 props. And actually, why use constants for this at all? Why not use an Environment Object instead?
Gordon
@Gordon OK let's imagine it's an external library over which you have no control :p
Artefacto
@Artefacto I'd never touch one of those ;)
Gordon
A: 

Yes, you can as suggested by @Artefacto but make sure that you use constants when you are sure property values won't change !!

Sarfraz
A: 

The best way to do this is to create an stdClass like class such as:

MyClass
{
    public function __set($key,$value)
    {
        $this->{$key} = $value;
    }
}

The you can just use

$Storage = new MyClass;

$Storage->SomeNewVar = "Some New Val";

echo $Storage->SomeNewVar;
RobertPitt
This doesn't answer the question at all.
Artefacto
yea I kind of mis understood what he was asking for, and its already been answered by yourself.
RobertPitt