开发者

Whats the meaning of 'static' when declaring a function

this is the code from the tutorial book.

class user {
    // return if username is valid format
    public static function validateUsername($username){
        return preg_match('/^[A-Z0-9]{2,20}$/i', $username);
    }
}

i wonder, what is the function of static?

it's to开发者_StackOverflow社区o bad the book i read didn't explain it :(


The end result is that you don't need to create an instance of the class to execute the function (there's more to it than that, but I'll let the manual cover those parts):

PHP: Static Keyword - Manual

In your example, you would call your function like:

user::validateUsername("someUserName");

Rather than having to create an instance and then calling the function:

$user = new user();
$user->validateUsername("someUserName");


Have you seen this: http://php.net/manual/en/language.oop5.static.php

Static methods and variables are useful when you 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.

source: http://bytes.com/topic/php/answers/495206-static-method-vs-non-static-method


Static functions are functions belonging to the class and not the object instance. They can be called without instancing the class by referring to it directly -

user::validateUsername(...);

Or using the self keyword from inside the class

self::validateUsername(...);

Static function are global functions in a way. You should use those sparingly as dependencies on static functions are harder to extract and make testing and reuse more difficult.

Read more in the PHP manual - the static keyword

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜