S
S
suhuxa12018-04-23 11:36:43
OOP
suhuxa1, 2018-04-23 11:36:43

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

3 answer(s)
A
alexalexes, 2018-04-23
@alexalexes

If you do static:

class any_class
{
  public static function add()
  {
  }
}

... then, in order to use the method, it is not necessary to create an object, the class of which this method belongs to, it is available if there is a class description.
And so once again create an object for any reason in order to use the add () method.
class any_class
{
  public function add()
  {
  }
}

$any_class_object = new any_class;
$any_class_object->add();

If the methods are common, and are used for every sneeze, of course, it is beneficial to make them static.

A
Alexander Sevirinov, 2018-04-23
@sevirinov

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.

D
Dmitry, 2018-04-23
@By_Engine

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 question

Ask a Question

731 491 924 answers to any question