Answer the question
In order to leave comments, you need to log in
What's the point of creating an object when you can use a static method?
Hello. Interested in the question:
Why and when do you need to create class objects, if, in fact, you can use static methods without creating objects? I do not really understand when it is more appropriate to create an object, and when to use statics.
For example:
class Test1 {
public static function result() {
return 2*2;
}
}
// Использование
$test1 = new Test1();
$test1->result(); //4
class Test2 {
public function result() {
return 2*2;
}
}
//Использование
Test2::result(); //4
Answer the question
In order to leave comments, you need to log in
Imagine an online store. There is an object: goods. Does the product have what? Well, for example, the price. If you make only the Product class and the getPrice() static method, then all products will have only one price. And if you use objects, then each product will have its own getPrice () method, which will give the price of this particular product.
And in general, since you ask such a question, you have not yet learned to think in OOP mode, you have a procedural approach in your head. "We need to write a function to calculate something." Get that thought out of your head. Look for objects in tasks, combine them into classes. Think about how these objects will affect each other
it is impossible to use $this in a static method, it is not logical
to think now what comes out of this
using the stat field, for example, you can count the total number of objects of this class
, so as the $count field is the same for all objects, creating a new object, we can simply increase this counter and at any time find out the value of the counter
class A {
$x;
static $count = 0;
staric $className = "A";
function __construct($x) {
$this->x = $x;
self::count += 1;
}
}
$one = new A(5);
$two = new A(10);
$one->x; // 5
$two->x; // 10
A::count; //2
$two::className(); // A (Начиная с PHP 5.3.0)
I recommend reading
the “static” keyword.
Regular properties, non-static, are inherent in each object individually (this car has 4 wheels, and that one has already been removed).
Static properties are inherent in the class itself, and not in specific objects (the number of cars on the planet is ... pieces, the total number of their wheels is ... pieces).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question