2
PHP allows me to have methods static
. Whose advantage is to have them accessible without the need to instantiate the class Documentation.
However, in the case of methods static
, I can use them both ways WITHIN THE CLASS ITSELF:
class Teste
{
private static metodoEstatico()
{
//código
}
public outroMetodo()
{
self::metodoEstatico();
$this->metodoEstatico();
}
}
PHP allows you to use static methods, both ways, within the class itself. Is there any difference in performance or something relevant to the two forms of use being within the class itself?
Relacioanda: Why can’t I use $this within a Static class?
– rray
Look, as far as I know, there is no difference in this example you gave. Just consider the comment above. If you put this inside the static method it will give error. This, to my knowledge, in any language...
– DiegoSantos
Good. In this case, I think I’ll keep the self::nameName() pattern for static methods. So the code reading will be clearer.
– alan
@rray In this case it makes no sense to use a "private Static" method. Because I won’t be able to use the main advantage of static methods, which is to use them without the class instance. Therefore, I must create "public Static" methods only when I do not need an instance to an Object. I am sure?
– alan
There is a difference, even you can use the
parent
. The self references the class of that function. The Parent references the parent class. The $this, as far as I know, cannot be used in this way. On the question of performance, I believe it is not relevant. Relevance becomes when using what is NECESSARY to use. Before I had a different view on this subject of php performance and micro-optimizations. I thought optimizations of this kind could make a difference in php. But it doesn’t.– Andrei Coelho
I was wrong. You can use the
$this
also.– Andrei Coelho
I’d have to change to
public
if you want to use the method outside the class or depending on the functionality you can create a simple function you do not need to associate it with any class. One way to organize would be to create a namespace only for 'loose functions'.– rray