Answer the question
In order to leave comments, you need to log in
What's the difference between public function and public static function?
I read a mountain of literature on OOP, I seem to have been working for more than a year, but static does not reach me. Here everything else comes, but there is no static. Why is it used?) I seem to have already forgotten about it, I usually always write in Laravel:
And then I look at the code in the course, and among the exact same functions I see one like this:
Its function in the code is used to add a comment on the site. And why not make it simple:
What will go wrong in this case? Thank you! public function xxx()
public static function add()
public function add()
Answer the question
In order to leave comments, you need to log in
If you do static:
class any_class
{
public static function add()
{
}
}
class any_class
{
public function add()
{
}
}
$any_class_object = new any_class;
$any_class_object->add();
Declaring the properties and methods of a class as static allows you to access them without creating an instance of the class. A class property declared as static cannot be accessed by an instance of the class (but a static method can be called).
Since static methods are called without creating an instance of the class, the $this pseudo-variable is not available inside a method declared as static.
Static methods and properties belong to a class, not to an object. The easiest way to explain this is with properties
class Foo {
static public $a = 0;
public $b = 0;
public function getA(){
return self::$a;
}
}
$Foo1 = new Foo;
$Foo2 = new Foo;
The property value "b" belongs to the object
$Foo1 -> b = 1;
echo $Foo2 -> b; // Outputs 0
The static property "a" belongs to the class and is available to any object of the class
Foo::$a = 15;
echo $Foo1 -> getA(); // 15
echo $Foo2 -> getA(); // fifteen
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question