views:

49

answers:

2

Hi everyone,

Ive looked and tried but I can't find an answer.

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?

A code example (which gives errors):

<?php

class Test {
    private $end="";

    function __construct($value) {
        $this->end=$value;
    }

    public function alert($value) {
        echo $value." ".$this->end;
    }
}

//this works:
$example=new Test("world");
$example->alert("hello");

//this does not work:
echo Test("world")::alert("hello");

?>
A: 

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.

cletus
i am creating an inline instance and discarding it immediately. i dont see why i need to allocate a variable to this process... is that just the way PHP/OOP is?
A: 

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()->doX();

Easy?

[]'s

Felipe Cardoso Martins
mykchan, this helped you?
Felipe Cardoso Martins