calling class method (with constructors) without object instantiation in php

In PHP, is it possible to call a class’ member function (when that class requires a constructor to receive parameters) without instantiating it as an object?

In Previous version php doesn’t have support to do this, but we can do like this,

You can use an “factory”, sample:


class Foo
   private $__aaa = null;

   public function __construct($aaa)
      $this->__aaa = $aaa;

   public static function factory($aaa)
      return new Foo($aaa);

   public function doX()
      return $this->__aaa * 2;

Foo::factory(10)->doX();   // outputs 20


you can try by using this code , here we are calling the function directly and storing in the variable.

$t = (new Test("Hello"))->foo("world");



Please follow and like us: