tags:

views:

51

answers:

3

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 too bad the book i read didn't explain it :(

+1  A: 

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

Ergo Summary
+5  A: 

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");
Justin Niessner
I would vote for this answer, but it means much more than that.
NickLarsen
@NickLarsen - Re-worded things a bit to make that more clear.
Justin Niessner
thank you very much for the link, it's explained so much :)
GusDe CooL
A: 

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

Eran Galperin