静态函数和PHP类外部的函数有什么区别? [英] What is the difference between static functions and function outside of a class in PHP?

查看:110
本文介绍了静态函数和PHP类外部的函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来从数据库中获取某些东西,但是我不了解PHP中静态函数和普通函数之间的区别.

I need to have method to get something from a database, but I don't understand the difference between static and normal functions in PHP.

示例代码

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
    }
}

和类之外的功能

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

如果我使用$item = Item::getDetail(15);$item = getDetail(15);-它们是相同的.

If I use $item = Item::getDetail(15); and $item = getDetail(15); — they're the same.

  1. 类之外的静态函数和函数之间有什么区别?
  2. 如果它们是不同的,那么如何使用静态函数和类之外的函数? (我会欣赏一个非常简单的示例.)
  3. 在类之外,静态和函数之间的性能属性是什么?哪个更好?

推荐答案

1)静态函数和普通函数有什么区别

虽然它们是函数,但我更喜欢将它们称为给定类的方法.一个是静态方法,另一个是实例方法.

While they are functions, I'd prefer to call them methods of a given class. One is a static method and the other is an instance method.

静态方法:$item = Item::getDetail(15);

实例方法:$item = getDetail(15);

(不过,请参阅上面注释中的FuzzyTree的正确语法.)

(refer to FuzzyTree's correct syntax above in the comments, however.)

2)如何使用静态函数和普通函数(如果您简单地举例就可以)

静态意味着您不必实例化(声明对象引用).也就是说,您可以简单地使用该方法.因此,在您的示例中,尽管答案可能是相同的,但如上所述,您调用该方法/函数的方式却有所不同.

Static means you do not have to instantiate (declare an object reference). That is, you can simply use the method. So, in your example, while the answer may be the same, the way you called that method/function is different, as you noted above.

例如,在Java中,您拥有Math类.它不需要实例化就可以使用,实际上您不知道,因为它的构造函数是私有的.您可以通过引用您要使用的类和方法名称来简单地使用方法,

In Java, for example, you have the Math class. It does not require instantiation to use, and in fact you cannot that I know of because its constructor is private. You can simply use a method by referencing the class and the method name you wish to use,

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

在PHP中可能是

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

Java:何时使用静态方法

3)在静态功能和普通功能之间询问性能.哪个更好?

更好取决于您的设计.如果您每次都想创建一个对象,那么您需要利用数字的力量而不是直接使用类来创建更多的内存使用量.我没有基准测试证明,但由于您在内存中的处理方式不同,因此这似乎合乎逻辑.我认为除非您执行许多复杂的操作,否则在现实世界中这并不重要.

Better is a matter of your design. If you have to create an object every time you want to do the power of a number that will create more memoryusage than simply using the class directly. I do not have benchmark proof, but it seem logical since you are not handling the method the same way in memory. I do not think it will matter in real world unless you are doing a lot of complicated actions.

静态方法与实例方法的性能

也可能使您感兴趣.

这篇关于静态函数和PHP类外部的函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆