Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Static and non Static functions and Objects

Tags:

php

static

What's the difference between these object callings?

Non Static:

$var = new Object; $var->function(); 

Static:

$var = User::function(); 

And also inside a class why should I use the static property for functions?

example:

static public function doSomething(){     ...code... } 
like image 328
Adam Halasz Avatar asked Dec 05 '10 22:12

Adam Halasz


People also ask

What are static functions in PHP?

Definition and Usage. The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

What is the difference between a static and non static function?

Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding. A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding.

Can static function access non static variables in PHP?

No. A static method will not have access to $this (as there is no $this to talk about in a static context). If you need a reference to the current object within the static method, it is not a static method.

Can static method be called by object PHP?

A property declared as static can not be accessed with an instantiated class object (though a static method can). This is why you are able to call the method on an instance, even though that is not what you intended to do.


1 Answers

Static functions, by definition, cannot and do not depend on any instance properties of the class. That is, they do not require an instance of the class to execute (and so can be executed as you've shown without first creating an instance). In some sense, this means that the function doesn't (and will never need to) depend on members or methods (public or private) of the class.

like image 192
Mark Elliot Avatar answered Oct 07 '22 22:10

Mark Elliot