DEV Community

Cover image for Create an object from a string variable in PHP
Yongyao Yan
Yongyao Yan

Posted on • Updated on • Originally published at codebilby.com

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;
    }

}
Enter fullscreen mode Exit fullscreen mode

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

$className = "Rectangle";
$class = new $className();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

$class->{"setLengthWidth"}($length, $width);
Enter fullscreen mode Exit fullscreen mode

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

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

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

Discussion (1)

Collapse
eshimischi profile image
eshimischi

Notice about forthcoming deprecation wiki.php.net/rfc/deprecate_dollar_...