How to dynamically set two attributes in a class in php?

Member

by domenico , in category: PHP General , 9 months ago

How to dynamically set two attributes in a class in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 months ago

@domenico 

In PHP, you can dynamically set two attributes in a class by using methods to set the attributes. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyClass {
    private $attribute1;
    private $attribute2;

    public function setAttributes($attr1, $attr2) {
        $this->attribute1 = $attr1;
        $this->attribute2 = $attr2;
    }

    public function getAttributes() {
        return array($this->attribute1, $this->attribute2);
    }
}

// Create an instance of the class
$myClass = new MyClass();

// Set the attributes dynamically
$myClass->setAttributes('value1', 'value2');

// Get the attributes
$attributes = $myClass->getAttributes();
print_r($attributes);


In this example, we have a class MyClass with two private attributes attribute1 and attribute2. We have a method setAttributes that takes two arguments and sets the values of the attributes accordingly. We also have a getAttributes method that returns an array containing the values of the attributes. By calling the setAttributes method with two values, we can dynamically set the attributes of the class.