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:

<?php

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

OR

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

 

 

3 thoughts on “calling class method (with constructors) without object instantiation in php”

  1. Pretty section of content. I just stumbled upon your site
    and in accession capital to assert that I get actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and even I achievement you access consistently quickly.

Leave a Reply

Your email address will not be published. Required fields are marked *