user2953119
user2953119

Reputation:

Add a property to a class instance

Let I've a class

class MyClass{
    //class implementation
}

I want to add the following method to this class:

public function addProperty($property){
    //This method will be set a property of a current MyClass instance with the name **property** and the value **$property**
}

Any idea to implement this method?

Upvotes: 0

Views: 76

Answers (3)

Sal00m
Sal00m

Reputation: 2916

public function addProperty($property){
    $this->{$property} = $property;
}

Upvotes: 0

Keyur Mistry
Keyur Mistry

Reputation: 926

Simply write that method in that class, create one object for that class. And where you want to use that method, just call that method by use of that object

$obj = new MyClass; $return = $obj->addProperty();

in that method if you want to use property, writ down like wise

public function addProperty($property){
    $this->property = $property;
}

it will gives you the property value

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

This method will be set a property of a current MyClass instance with the name property and the value $property

Its very basic, do:

public function addProperty($property){
  $this->property=$property;    // declare it as well
}

Or do you mean property as just a placeholder? you could then do

  $this->{$property}=$property; 

Upvotes: 1

Related Questions