Skip to content
Advertisement

How to pass arguments to anonymous PHP class constructor?

I wrote small anonymous class. now i want to pass some arguments to anonymous class . how could i accomplish this task . Currently i m using PHP 8.1 version

<?php

$myObject = new class {
    public function __construct($num)
    {
        echo 'Constructor Calling'.$num;
    }

    public function log(string $text){
        return $text;
    }

};


var_dump($myObject->log("Hello World"));

Advertisement

Answer

Because your class require $num argument in construct, you need to pass it when you instanciate your object.

<?php

$myObject = new class(1) {
    public function __construct($num)
    {
        echo 'Constructor Calling'.$num;
    }

    public function log(string $text){
        return $text;
    }

};


var_dump($myObject->log("Hello World"));

Will result

Constructor Calling1
string(11) "Hello World"

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement