Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

php

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!

like image 982
Michael Lynch Avatar asked Feb 12 '26 05:02

Michael Lynch


2 Answers

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

$var = Class::someFunction();
like image 84
Matt Avatar answered Feb 14 '26 20:02

Matt


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();
like image 32
Alfwed Avatar answered Feb 14 '26 20:02

Alfwed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!