js

Sunday, December 17, 2023

Expalin object chaining in php.

 Q. Expalin object chaining in php.
Answer:
In PHP, object chaining refers to the practice of calling multiple methods on an object in a single line. To enable object chaining, each method in the class should return the instance of the object ($this). This way, you can call another method on the same object immediately after the first one.

Here's a simple example:

class MyClass {
    private $value;

    public function setValue($value) {
        $this->value = $value;
        return $this; // Return $this for chaining
    }

    public function multiplyBy($factor) {
        $this->value *= $factor;
        return $this; // Return $this for chaining
    }

    public function getResult() {
        return $this->value;
    }
}

// Example of chaining
$obj = new MyClass();
$result = $obj->setValue(5)->multiplyBy(3)->getResult();

echo $result; // Output: 15


In this example, the setValue and multiplyBy methods both return $this, allowing you to chain them together. Finally, the getResult method is called to retrieve the result.

Remember, for object chaining to work, each method in the chain must return the object instance ($this). If a method returns something else, you won't be able to chain additional methods onto it.

No comments:

Post a Comment

SEBA HSLC Question Paper Assamese 2022