Webdesign7 London
Webdesign7 London

Reputation: 775

php class names , what's the difference

I am a new in terms of PHP OOP programming, i don't understand when and how the following class names are and when shall i use them :

$a = new Classname();
$a = new Classname;

$a = ClassName::function();
$a = ClassName::getInstance();

Many thanks and sorry for silly question:

Upvotes: 1

Views: 101

Answers (3)

Thomas
Thomas

Reputation: 2984

For:

$a = new Classname();
$a = new Classname;

These are just 2 different ways of saying the same thing: Create a new reference to class "Classname" without any parameters (php is more lenient in regards to if () and parameters must be given or not than many other programming languages).

For:

$a = ClassName::function();
$a = ClassName::getInstance();

These two are static calls of the functions "function()" and "getInstance()", thus $a would be set to the appropriate return value of these function. Static means that you can use the functions without referening the class itself (thus $b=ClassName(); $a=$b->function() is not needed instead you can just write it as you did above).

Upvotes: 1

lll
lll

Reputation: 12889

These are identical.

$a = new Classname();
$a = new Classname;

You can use them interchangeably when the class constructor does not take, or does not require other parameters.

Example:

class Classname
{
    public function __construct($var = null)
    {
        // ..
    }

    static public function getInstance()
    {
        // ..
    }
}

In this case you can use $a = new Classname; and $var will take the default value, or $a = new Classname('hello') and $var will be equal to the value passed.


These are both static method calls.

$a = ClassName::function();
$a = ClassName::getInstance();

One calls a method called "function" (which cannot exist - it is a reserved word), the other calls a method named "getInstance". When you use them really depends on what the methods do.

Static methods can be called without creating an object instance.

I.e.

Classname::staticMethod();

versus

$obj = new Classname;
$obj->method;

Upvotes: 10

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

As for

$a = new Classname(); 
$a = new Classname;

No difference if __construct() has no arguments to receive.


As for

$a = ClassName::function();
$a = ClassName::getInstance();

this is just normal call of static methods

Upvotes: 4

Related Questions