Create an object from a string variable in PHP

Create an object from a string variable in PHP

In PHP, objects can be created from string variables. It provides a very convenient way for you to define rules in text and handle requests dynamically. In this post, we show you how to do it.

Create an object from a string variable

Supposed we have a class called Rectangle, it is for a rectangle shape and it calculates its area.

class Rectangle
{
    private $length;
    private $width;

    public function setLength($l) {
        $this->length = $l;
    }

    public function setWidth($w) {
        $this->width = $w;
    }

    public function setLengthWidth($l, $w) {
         $this->length = $l;
         $this->width = $w;
    }

    public function getArea() {
        return $this->length * $this->width;
    }

}

You can use a string variable to create the Rectangle object like this:

$className = "Rectangle";
$class = new $className();

Also, a function in a class can be called by using a string variable. If you want to call the function setLength() and setWidth() in the class Rectangle, you can do as follows:

$length = 10;
$width = 3;

$setLength = "setLength";
$setWidth = "setWidth";

$class->{$setLength}($length);
$class->{$setWidth}($width);

Or, you can just use a string in the {} to call a function like this:

$class->{"setLengthWidth"}($length, $width);

To calculate the Rectangle's area, the function getArea() can be called as follows:

echo "The area is: " . $class->{"getArea"}(); // The area is: 30

Create rules and call functions dynamically

Here, we show you an example how to call functions dynamically based on the request.

...

For the rest of the content, please go to the link below: https://www.codebilby.com/blog/a42-create-object-from-variable-name

Did you find this article valuable?

Support Yongyao Yan by becoming a sponsor. Any amount is appreciated!