Cameron
Cameron

Reputation: 28783

DIfference between way classes are called in CakePHP

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

Upvotes: 0

Views: 51

Answers (1)

David Yell
David Yell

Reputation: 11855

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.

Upvotes: 2

Related Questions