oop - The getMessage() function in PHP being static referenced by object?

796

On the PHP documentation the function getMessage of Exception class is given as:

final public string Exception::getMessage ( void )

Since there is a scope resolution operator this means it is a static function and when we catch the exceptions in catch block then we do something like

$e->getMessage();

But in PHP we cannot reference the static functions with the object.

453

Answer

Solution:

The scope resolution operator:: needs to be used to call static methods because there is not an associated instance to call them from.

Similarly, it is used when describing the signature of a method because there is no instance to use the-> (object scope) operator. But it doesn't say or imply a method is static.

Thestatic keyword does that.getMessage is not a static method, and you shouldn't call it statically. TheException class has nostatic methods or properties. Linky.

773

Answer

Solution:

It's not because it's written with the scope resolution operator inside the PHP docs, that it is a static function.

If you watch the docs carefully, you'll see that every method is with that operator.
If you want to be sure, you need to check the docs of the object itself: https://secure.php.net/manual/en/class.exception.php

There you can see this:

/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )

If there was a static method, it would be written here.

Another example is the DateTime object: https://secure.php.net/manual/en/class.datetime.php
Here you can see that the keywordstatic is inside the method list.

People are also looking for solutions to the problem: PHP reading big txt file, memory solution

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.