GusDeCooL
GusDeCooL

Reputation: 5758

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

Upvotes: 3

Views: 1675

Answers (3)

Eran Galperin
Eran Galperin

Reputation: 86805

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

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245389

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");

Upvotes: 13

SW4
SW4

Reputation: 71140

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

Upvotes: 1

Related Questions