Michael Lynch
Michael Lynch

Reputation: 1743

PHP Syntax: $var = (new Class())->someFunction();

Basically what i mentioned in the title is what i am trying to do and im not sure if its possible to do or not.

I have:

$myClass = new Class();
$var = $myClass->someFunction();

But then i never use $myClass again an i could unset it to free up memory. however im trying to clean up my code at the same time and wondered if the following is valid

$var = (new Class())->someFunction();

And if its not what would you guys suggest?

Thanks!

Upvotes: 2

Views: 267

Answers (7)

Martin
Martin

Reputation: 6687

No, it's not possible in versions < PHP 5.4.0

In PHP >= 5.4.0 you can de-reference arrays and use the syntax you listed above.

That said, from your description it sounds like you want a static function.

Upvotes: 1

Marko Jovanović
Marko Jovanović

Reputation: 2664

Yes you can call a method on a new object, but it is only supported in PHP >= 5.4

class Test {
   public function hello() {
    return "hello";
   }
} 

$var = (new Test())->hello();

echo $var; // prints hello

Upvotes: 1

Sammaye
Sammaye

Reputation: 43884

$var = (new Class())->someFunction();

I believe this is perfectly valid syntax as of php 5.4.

As can be seen here: http://www.php.net/manual/en/migration54.new-features.php

Upvotes: 2

Bonius
Bonius

Reputation: 121

Remember that you can also use the $myClass in pretty much every instance where you need a return value or iteration. Example:

foreach($myClass->fetchUsers() as $user){
}

if($myClass->userLoggedIn()){
}

Alot more nifty than doing a

$var = $myClass->fetchUsers();
foreach($var as $user){}

Upvotes: 0

Alfwed
Alfwed

Reputation: 3282

There's no native way to do it

But

You can achieve what you want to do with a factory method.

class a {
    public static create() {
        return new self();
    }
    //....
}

$something = a::create()->foo();

Upvotes: 2

Matt
Matt

Reputation: 7040

You can always declare someFunction() as a static method.

$var = Class::someFunction();

Upvotes: 8

Narf
Narf

Reputation: 14752

That's a not valid syntax. But why don't you just reuse the variable that you assigned your object to?

$var = new Class();
$var = $var->someFunction();

Upvotes: 0

Related Questions