What is the difference between static functions and a function outside a class in PHP?

I need to have a way to get something from the database, but I do not understand the difference between static and normal functions in PHP.

Code example

class Item {
    public static function getDetail($arg) {
        $detail = $this->findProductId($arg);   
        return $detail;
    }

    private function findProductId($id) {
        //find product_id in database where id = $arg
        //return detail of product
    }
}

and function outside the class

function getDetail($arg) {
    $detail = findProductId($arg);
    return $detail;
}

If I use $item = Item::getDetail(15);and $item = getDetail(15);- they are the same.

  • What is the difference between static and function outside the class?
  • If this is the difference, how to use static functions and functions outside the class? (I would appreciate a really simple example.)
  • What are the performance properties between static and function outside the class? What's better?
+4
source share
6 answers

1) What is the difference between static function and normal function

, . - , - .

: $item = Item::getDetail(15);

: $item = getDetail(15);

(., , FuzzyTree .)

2) ( )

Static , ( ). . , , , , /, , .

Java, , Math. , , . , , ,

Math.pow(d1, d2);  //no instantiation needed

PHP ,

MyClass::pow(d1,d2); //no instantiation needed

Java:

3) . ?

. , , , . , , . , , .

.

+9

, :

class Item {
    public static function getDetail($arg){}
}

, :

function getDetail($arg){}

, . Item::getDetails($arg) , . , , , , .

, , , , - .

+2

1. : $this, . $this, Fatal error: , E_strict.

2. , . .

3. , - , - . - PHP , , , . Static

+1

, , .

$item = getDetail(15); , detDetail - , .

, 5.4.0. . http://www.micro-optimization.com/global-function-vs-static-method

+1

, - ().

OOP , , , , .

, "A", "A", .

, , .

? , , . - .

: Car BMW. THE BMW, .

, , . , , .

+1

, , , . , GC, - - gc , . .

, "". ...

0

Source: https://habr.com/ru/post/1542389/


All Articles