4

Is there a way to call a method on a temporary declared object without being forced to assign 1st the object to a variable?

See below:

class Test
{
   private $i = 7;      
   public function get() {return $this->i;}   
}

$temp = new Test();
echo $temp->get(); //ok

echo new Test()->get(); //invalid syntax
echo {new Test()}->get(); //invalid syntax
echo ${new Test()}->get(); //invalid syntax

9 Answers 9

8

I use the following workaround when I want to have this behaviour.

I declare this function (in the global scope) :

function take($that) { return $that; }

Then I use it this way :

echo take(new Test())->get();
0
7

What you can do is

class Test
{
   private $i = 7;      
   public function get() {return $this->i;}

   public static function getNew() { return new self(); }
}

echo Test::getNew()->get();
3
  • What's self() function? It's undocumented in PHP. Did u mean { return new Test(); } Feb 13, 2010 at 15:34
  • 1
    It's not self() function, it's creating of instance of self class - the class we're in. new self() is synonymous to new Test() here, with additional bonus of not having to change it when you rename Test class to OldTest ;-) Feb 18, 2010 at 12:51
  • @Krelin: cool, I thought self was only a keyword to call static vars/methods inside class! :) Feb 21, 2010 at 15:49
4

Why not just do this:

class Test
{
   private static $i = 7;      
   public static function get() {return self::$i;}   
}

$value = Test::get();
3
  • +1 because it's the only thing that makes sense in my opinion. Added static keyword though
    – Gordon
    Feb 7, 2010 at 18:27
  • I cannot help it, but using classes this way always makes me feel a bit uncomfortable. It feels like using them not in a proper way. Plus, this may not be what the OP wanted, since a second instance of the class may need to store a different value for $i (in case he left that part out for brevity).
    – Dan Soap
    Feb 7, 2010 at 23:19
  • sorry, but i really don't understand your answer, but since you got 3 votes up I wonder what I'm missing. I don't want a static $i, moreover you class is returing the variable and not the object. Aug 18, 2010 at 13:02
3

Unfortunately, you can't do that. It's just the way PHP is, I'm afraid.

3

No. This is a limitation in PHP's parser.

2

i often use this handy little function

 function make($klass) {
    $_ = func_get_args();
    if(count($_) < 2)
        return new $klass;
    $c = new ReflectionClass($klass);
    return $c->newInstanceArgs(array_slice($_, 1));
 }

usage

make('SomeCLass')->method();

or

make('SomeClass', arg1, arg2)->foobar();
0
1

Impossible and why would you create an object this way at all?

The point of an object is to encapsulate unique state. In the example you gave, $i will always be 7, so there is no point in creating the object, then getting $i from it and then losing the object to the Garbage collector because there is no reference to the object after $i was returned. A static class, like shown elsewhere, makes much more sense for this purpose. Or a closure.

Related topic:

7
  • @stereofrog As Andi Gutmans' a founder of Zend Technologies, I trust him to know why he's saying that
    – Gordon
    Feb 7, 2010 at 22:53
  • @stereofrog Well, I'm not part of the core community. I just don't have sufficient insight into PHP's inner workings to have reason to doubt Andi's statement. And I still fail to see how (new foo)->bar() would be adding any benefit over a static method or a closure.
    – Gordon
    Feb 7, 2010 at 23:23
  • @stereofrog banned != not introduced. That's a notable difference. Personally, I don't see any added value in this notation. Sure, it's less verbose, but it is also less readable. $a = new Foo; $b = $a->bar(); $c = $b[25]; $c('blah'); will achieve the same thing. In this regard, it doesn't make PHP any more complete to have it. You can even do class A { public function b($c) { return strtoupper($c); } } $a = array( create_function('', 'return new A;') ); echo $a[0]()->b('foo'); if you want to screw up readability at all cost.
    – Gordon
    Feb 8, 2010 at 8:13
  • @Gordon Mine was just a simple example class because I wanted the subject of the question to remain on a possible PHP sintax. I understood there is no possible sintax to accomplish this task. FYI: an example were creating object on the fly could be useful is a Date class. Constructor could return today date when called with no parameters, if I want to print the today date, I could do: echo "Today is: " . new Date()->getAsDDMMYYYY(); //sadly this is invalid sintax :) Feb 8, 2010 at 10:49
  • @Marco I'm still not convinced this shouldn't be in a static method or closure then. Date is not a good example anyway, because you can achieve this easily with date('dmy').
    – Gordon
    Feb 8, 2010 at 11:48
1

This is an old question: I'm just providing an updated answer.

In all supported versions of PHP (since 5.4.0, in 2012) you can do this:

(new Test())->get();

See https://secure.php.net/manual/en/migration54.new-features.php ("Class member access on instantiation").

0
0

This has come up very recently on php-internals, and unfortunately some influential people (e. g. sniper) active in development of PHP oppose the feature. Drop an email to [email protected], let them know you're a grownup programmer.

1
  • Some legacy code might rely on 2x2==5, so you have to be accommodating.
    – JAL
    Feb 7, 2010 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.