0

I have seen classes called like:

$Class = ClassName::methodName();

and also

$Class = new ClassName();
$Class->methodName();

What is the difference between the two?

The reason I ask is because in CakePHP, the CakeEmail is called like the second example, but all the other classes are called like the first...

e.g. http://book.cakephp.org/2.0/en/core-utility-libraries/email.html and http://book.cakephp.org/2.0/en/core-utility-libraries/security.html

Cameron
  • 24,868
  • 91
  • 263
  • 449
  • possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – PeeHaa Aug 13 '13 at 21:39
  • @PeeHaa I'm more interesting in why the difference in CakePHP for all other classes except the CakeEmail one. – Cameron Aug 13 '13 at 21:40
  • `::` is used to reference [`static`](http://php.net/manual/en/language.oop5.static.php) functions and properties. – Sammitch Aug 13 '13 at 21:40
  • possible duplicate of [Difference in Class Calling PHP](http://stackoverflow.com/questions/13043537/difference-in-class-calling-php) – mario Aug 13 '13 at 21:40
  • Because Cake is one on the worst frameworks out there and it is full of bad practices. Hence the static calling of (almost) everything. – PeeHaa Aug 13 '13 at 21:42
  • @PeeHaa This is just simply not true. If you want to hate monger, go look at Laravel, the static framework! – David Yell Aug 13 '13 at 21:44
  • [Oh I have looked at Laravel.](http://chat.stackoverflow.com/transcript/11?m=11114087#11114087) ;-) – PeeHaa Aug 13 '13 at 21:46

1 Answers1

2

This is the difference between a static method and a regular method.

A static method doesn't require the class to be instantiated for the method to be used. Where as regular methods in a class need the class to be instantiated.

You can read more in the PHP Manual.

Static keyword, http://php.net/manual/en/language.oop5.static.php

Actually not all classes are static in CakePHP, quite the opposite in fact. There are a few static methods.

The reason the CakeEmail class requires a class instance to be instantiated is that it uses class variables and other methods in the class to set the various parts of the email before it is sent. Thus some settings will be stored in __constructor() which is run when the class is instantiated.

As other methods in the class, such as adding a subject will write class variables, an instance of the class needs to exist first.

David Yell
  • 11,513
  • 11
  • 59
  • 95