Possible Duplicate:
In PHP, whats the difference between :: and -> ?
This a continuation from my previous question - however I think its unique enough to warrant a new question.
What is the difference between:
Message::listMessages();
and
$message->listMessages();
I'm creating a mini-cms and I want a s开发者_JAVA技巧ystem that displays errors in a uniform fashion.
Cheers, Keiran
Static methods come handy when we want to share information between objects of a class, or want to represent something that's related to the class itself, not any particular object.
The difference between the two is in the way they are invoked.
For example, Message::listmessages()
is a static method and can be called like this:
$messages = Message::listmessages($args);
You do not need to first make an object of class Message, in order to use the above. Also, note that this should be used when you want to return a result on definite pre-configured variables, and is not based on properties of class Message
However, $message->listmessages()
is an instance method and can be called like this:
$message = new Message();
$messages->$args = $args
$messages= $message->listmessages();
This is used for generic occassions when you want to call a function on runtime properties of class Message.
As i understood your question,
we are using this way Message::listMessages();
in C
and C++
but right syntax we are using in PHP
is $message->listMessages();
Thanks.
I assume your class Message
is defined like this:
class Message {
//...
static function listMessages() {
//...
}
//...
}
They are same, they both call the static method listMessages
from Message
, however, $message->listMessages()
requires less lookup.
According to a test, you cannot declare two methods with same names, one static and one member:
$ php5-cgi
<?php
class A { static function f() { }
function f() { } }
?>
PHP Fatal error: Cannot redeclare A::f() in - on line 2
Status: 500 Internal Server Error
X-Powered-By: PHP/5.3.2-1ubuntu4.5
Content-type: text/html
Message::listMessages() is a static function so it should be used when listMessages() is disregarding you're object propretyes , ie. return some class constants or variables or ... anything you like . ( static means it should have the same output for all instances of Message class )
$message->listMessages() may use you're object propretyes so output could be different for two different objects of the same Message class with different propretyes ( say $messages and $messages1 ) .
This is calling a static method, i.e. a method on a class:
Message::listMessages();
This is calling an instance method, i.e. a method on an object (aka instance of a class):
$message->listMessages();
The class Message
is calling its own method without an object means the method is static no object have rights to call this method only class can call.
Message::listMessages();
The object of class Message
is calling the public method
$message->listMessages();
精彩评论