Below are the examples of php class code that is static method and non static method.
Example 1:
class A{
//None Static method
function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>";
} else {
echo "\$this is not defined.<br>";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is defined (A)
$this is not defined.
Example 2:
class A{
//Static Method
static function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>\n";
} else {
echo "\$this is not defined.<br>\n";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is not defined.
$this is not defined.
I am trying to figure out what is the difference between these two Classes.
As we can see on the result of the none static method, the "$this" was defined.
But on the other hand the result on the static method was not defined even they were both instantiated.
I am wondering why they have different result since they were both instantiated?
Could you please enlighten me on what is happening on these codes.
Before we go any further: Please, get into the habbit of always specifying the visibility/accessibility of your object's properties and methods. Instead of writing
Write:
first off, your first example
A::foo
will trigger a notice (calling a non-static method statically always does this).Secondly, in the second example, when calling
A::foo()
, PHP doesn't create an on-the-fly instance, nor does it call the method in the context of an instance when you called$a->foo()
(which will also issue a notice BTW). Statics are, essentially, global functions because, internally, PHP objects are nothing more than a Cstruct
, and methods are just functions that have a pointer to that struct. At least, that's the gist of it, more details hereThe main difference (and if used properly benefit) of a static property or method is, that they're shared over all instances and accessible globaly:
As you can see, the static property
$bar
can't be set on each instance, if its value is changed, the change applies for all instances.If
$bar
were public, you wouldn't even need an instance to change the property everywhere:Look into the factory pattern, and (purely informative) also peek at the Singleton pattern. As far as the Singleton pattern goes: Also google why not to use it. IoC, DI, SOLID are acronyms you'll soon encounter. Read about what they mean and figure out why they're (each in their own way) prime reasons to not go for Singletons
Sometimes you need to use a method but you don't want call class, because some functions in a class called automatically like as __construct, __destruct,... (Magic Methods).
called class:
Don't called class: (just ran foo() function)
http://php.net/manual/en/language.oop5.magic.php