Home > Net >  How to pass arguments to anonymous PHP class constructor?
How to pass arguments to anonymous PHP class constructor?

Time:12-13

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"));

CodePudding user response:

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"

  •  Tags:  
  • php
  • Related