Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling static method non-statically

I have a child class that extends a class with only static methods. I would like to make this child class a singleton rather than static because the original developer really wanted a singleton but used static instead (obvious because every method in the static class calls the Init() function (basically a constructor)).

Most of the methods in the parent don't need to be overwritten in the child, but I would like to avoid having to write methods like this:

public function Load($id)
{
     return parent::Load($id);
}

when I would prefer not to overwrite the method at all and just use:

$child->Load($id);

Is it possible to call a static method non-statically? Is it possible to extend a static object with an instance object? I know I can try it and it will likely work (PHP is very forgiving), but I don't know if there is anything I should be concerned about.

like image 844
Mike Avatar asked Mar 29 '13 16:03

Mike


People also ask

Can I call static method in non-static method?

Characteristics of Static Methods A static method can call only other static methods; it cannot call a non-static method. A static method can be called directly from the class, without having to create an instance of the class.

Can you call a static method without an instance?

Static methods are methods that are associated with a class rather than an object. They are declared using the keyword static. We can call static methods without creating an instance of the class.

What is the difference between calling static methods and non-static methods?

A static method is a class method and belongs to the class itself. This means you do not need an instance in order to use a static method. A non-static method is an instance method and belongs to each object that is generated from the class.

Can we call non-static method without creating object?

Non-static methods can access any static method and static variable, without creating an instance of the object.


1 Answers

  • Can you inherit static methods?

Yes

  • Can you override static methods?

Yes, but only as of PHP 5.3 do they work as you would expect: http://www.php.net/manual/en/language.oop5.static.php (ie. self binds to the actual class and not the class it's defined in).

  • Is it possible to call a static method non-statically?

Yes, but will lose $this. You don't get a warning (yet) but there also isn't really a reason to call it the wrong way.

like image 163
Halcyon Avatar answered Oct 30 '22 09:10

Halcyon