Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Two part answer.

First, about the titular question: calling a static method non-statically is perfectly fine; @SamDark's comment is correct. It does not produce a warning, nor does it cause any kitten murdering. Try it:

<?php

class test {
    public static function staticwarnings(){
        echo "YOU ARE (statically) WARNED!
";
    }
}

error_reporting(E_ALL);

$test = new test();
echo "

calling static non-statically
";
$test->staticwarnings();

If you had an instance reference, $this, in that static method, then you would get a fatal error. But that is true regardless of how you call it.

Once again, there isn't a warning, nor any kitten killed.


Second part of the answer:

Calling an overridden parent function from an overriding child class requires something called "scope resolution". What the OP is doing in their method is NOT calling a static method. (Or at least, it doesn't have to be; we can't see the parent implementation). The point is, using the parent keyword is not a static call. Using the :: operator on an explicit parent class name is also not a static call, if it is used from an extending class.

Why is that documentation link so strangely named? It's literally Hebrew. If you've ever run into an error related to it, you might have observed the delightfully-named parser error code T_PAAMAYIM_NEKUDOTAYIM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...