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

岁酱吖の 提交于 2019-11-29 02:28:30

Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D

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

Just do this (in PHP >= 5.4):

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

You can't call an instance-level method without an instance. Your syntax:

echo Test("world")::alert("hello");

doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the alert() method has no implicit this instance.

Assuming:

class Test {
  public function __construct($message) {
    $this->message = $message;
  }

  public function foo($message) {
    echo "$this->message $message";
  }
}

you can do:

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

but PHP syntax doesn't allow:

new Test("Hello")->foo("world");

which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.

I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line:

$newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : '');

Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code:

function convertDate($oldDateString,$newDateFormatString) {
    $d = new DateTime($oldDateString);
    return $d->format($newDateFormatString);
}

$myNewDate = convertDate($myOldDate,'F d, Y');

I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!