Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Call Function in a Class - Is there a simpler way?

I am very new to OOP and very rusty on PHP. I was wondering if this is a valid method to call a function from a class?

class newclass {
    public function testfunc {
        return '1';
    }
}

Could I call it like this:

echo testfunc->newclass();

or like this:

echo newclass()::testfunc;

I always see it defined in examples like below and it seemed like extra code?:

$this = new newclass();
$this->testfunc();
echo $this;

Any help would be greatly appreciated as I'm just starting to wrap my head around this OOP thing. If I'm out to lunch maybe someone could suggest a link to a really good guide for a true beginner in classes/OOP. Thanks!

like image 613
DieselPower Avatar asked Dec 31 '25 00:12

DieselPower


1 Answers

Both ways work and have their use cases.

Your first case is a regular function call using an instance of a class, your second case is a call to a static function.

Static should be used with care and the use of it is very often a sign that refactoring/redesign is necessary.

The point of object oriented programming is to model the world by writing classes (blueprints) and then create as many independent instances of that class with the word new as needed. Each instance is a little organism with the DNA of the class and you can call the same class method on every single instance without influencing the other instances.

A static call however is not related to an instance of a class and therefore there is no object being used. It's a global call of some tool functionality and in fact breaks the idea of encapsulation.

So, I'm not saying there are no use cases for static classes and methods but they should be used with care.

like image 180
markus Avatar answered Jan 02 '26 13:01

markus



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!