简体   繁体   English

何时在PHP中使用Class vs. Function

[英]When to use a Class vs. Function in PHP

The lightbulb has yet to go on for this... 灯泡尚未继续......

I'd really love an easy to understand explanation of the advantage to using a class in php over just using functions. 我真的很喜欢一个易于理解的解释,在php中使用一个类而不仅仅是使用函数。

Here's a simple example of the thought I'm having now and am wondering if a class is more efficient: 这是我现在想到的一个简单的例子,我想知道一个班级是否更有效率:

Say I have a mini calendar widget that I've built in php. 假设我有一个我用PHP构建的迷你日历小部件。 I'm thinking about calling the function miniCal('arrayVars1', 'var2') . 我正在考虑调用函数miniCal('arrayVars1', 'var2') But I might do it twice on that page. 但我可能会在那个页面上做两次。 Do use fewer resources by using a class here, create new instances of it? 通过在这里使用类来使用更少的资源,创建它的新实例?

What tree should I be barking up here, because I feel like right now the tree is a brick wall... 我应该在这里吠叫什么树,因为我觉得现在这棵树是一堵砖墙......

Classes are used for representing data as objects. 类用于将数据表示为对象。 If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. 如果您要表示类似用户数据或拍卖出价的内容,则创建User对象或AuctionBid对象可以更轻松地将这些数据保存在一起,在代码中传递它,并使读者更容易理解。 These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class). 这些类将具有属性(数字字段,如数字,字符串或其他对象)以及方法(可以在任何类上操作的函数)。

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. 类通常不会在性能方面提供任何好处,但它们也很少有任何负面影响。 Their real benefit is in making the code clearer. 他们真正的好处是使代码更清晰。

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry . 我建议你阅读PHP5面向对象编程指南Wikipedia OOP条目

A common thing to do since PHP5 was to create classes that act as libraries. 自PHP5以来,常见的事情是创建充当库的类。 This gives you the benefit of organizing your functionality and taking advantage of class features like __autoload(); 这为您提供了组织功能和利用__autoload()等类功能的好处。

For example, imagine you have two functions for encrypting and decrypting data. 例如,假设您有两个用于加密和解密数据的函数。 You can wrap them in a class (let's call it Encryption) and make them static functions. 您可以将它们包装在一个类中(让我们称之为加密)并使它们成为静态函数。 You can then use the functions like this (notice no initialization is needed (ie $obj = new Encryption)): 然后你可以使用这样的函数(注意不需要初始化(即$ obj = new Encryption)):

$encrypted_text = Encryption::encrypt($string);

and

$decrypted_text = Encryption::decrypt($string);

The benefits of this are: 这样做的好处是:

  1. Your encryption functionality is grouped together and organized. 您的加密功能组合在一起并进行组织。 You, and anyone maintaining the code, know where to find your encryption functionality. 您和维护代码的任何人都知道在哪里可以找到您的加密功能。
  2. This is very clear and easy to read. 这非常清晰易读。 Good for maintainability. 有利于可维护性。
  3. You can use __autoload() to include the class for you automatically. 您可以使用__autoload()自动为您包含该类。 This means you can use it like it was a built in function. 这意味着您可以像使用内置函数一样使用它。
  4. Because it is contained in its own class and own file it is reusable and can easily be ported to new projects. 因为它包含在自己的类和自己的文件中,所以它是可重用的,并且可以很容易地移植到新项目中。

Using classes is a good way for grouping your functions. 使用类是分组函数的好方法。

The difference lies in the usage of the programming paradigm. 不同之处在于编程范式的使用。 Classes are necessary in OOP but are not necessary in the Procedural paradigm. 类在OOP中是必需的,但在程序范例中不是必需的。 In the Procedural paradigm you can group functions in a file, which can be seen as a module. 在Procedural范例中,您可以将函数分组到一个文件中,该文件可以看作是一个模块。

--- edit --- ---编辑---

You could use procedural paradigm . 你可以使用程序范式 Classes are not really needed in this paradigm. 在这个范例中并不真正需要类。

function miniCal($string_1, $string_2){
//do something   
}

//invoke function
miniCal('arrayVars1', 'var2');

You could use OOP paradigm . 你可以使用OOP范例 Classes are needed. 需要课程。

class Calculation {

public static function miniCal($string_1, $string_2){
    //do something   
    }
}

//invoke function
Calculation::miniCal('arrayVars1', 'var2');

Conclusion 结论

Both paradigma's work, but the OOP example from the above is using a Calculations object which contains all calculations methods (functions). 这两个范例的工作,但上面的OOP示例使用包含所有计算方法(函数)的Calculations对象。 The Calculations object groups calculation functions, thus keeping them in one place. Calculations对象对计算函数进行分组,从而将它们保存在一个位置。

The OOP paradigm in this example obeys to a principles called "Solid responsibility". 本例中的OOP范例遵循一种称为“坚定责任”的原则。 The idea behind this is to keep the code elegant, maintainable and readable. 这背后的想法是保持代码优雅,可维护和可读。

Functions are the meat of your application and classes are more like the plate. 函数是您应用程序的核心,类更像是板块。 It's messy to eat meat without a plate. 没有盘子吃肉是很麻烦的。 But if you don't have any meat, you don't have a meal. 但如果你没有肉,你就没有吃饭。

If you have 500 functions in your applications, you're probably going to want to group at least half of them into larger collections for ease of access. 如果您的应用程序中有500个函数,那么您可能希望将至少一半的函数分组到更大的集合中以便于访问。 You can devise common naming conventions ("Encryption_Encrypt", "Encycryption_Decrypt", etc.)...but classes are just easier. 您可以设计常见的命名约定(“Encryption_Encrypt”,“Encycryption_Decrypt”等)......但类更容易。 If you only have 12 functions in your application, you could probably survive with only 1 or classes, if any. 如果您的应用程序中只有12个函数,那么只有1个或类(如果有的话)可能存在。

I don't often need to store data/properties in classes. 我不经常需要在类中存储数据/属性。 I tend to store those in the database. 我倾向于将它们存储在数据库中。 So I haven't take advantage of that aspect of classes very often. 所以我没有经常利用课程的这一方面。

Classes also allow polymorphism, which can be helpful. 类也允许多态,这可能会有所帮助。 If you have several classes that are extremely similar, or several variations on a class, you can save code...without having to construct some multi-purpose, Frankenstein-like class. 如果你有几个非常相似的类,或者类的几个变种,你可以保存代码......而不必构建一些类似Frankenstein的多用途类。

I have a list of places you would use OOP-Style Classes in my answer to this question: https://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/2035482#2035482 在我对这个问题的回答中,我有一个你会使用OOP风格类的地方列表: https//stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/2035482#2035482

Basically, whenever you want to represent an object that has things in it. 基本上,每当你想要表示一个包含东西的对象时。 Like a database variable that has a connection in it that is unique. 就像一个数据库变量,它具有唯一的连接。 So I would store that so I can make sure that the mysql_query uses the correct connection everytime: 所以我会存储,所以我可以确保mysql_query每次都使用正确的连接:

class MySQL extends Database
{
    public function connect($host, $user, $pass, $database)
    {        
        $this->connection = mysql_connect($host, $user, $pass);
        $this->select_db($database);
    }

    public function query($query)
    {
        return mysql_query($query, $this->connection);
    }

    public function select_db($database)
    {
        mysql_select_db($database);
    }    
}

Or maybe you want to build a Form, you could make a form object that contains a list of inputs and such that you want to be inside the form when you decide to display it: 或者您可能想要构建一个Form,您可以创建一个包含输入列表的表单对象,以便在您决定显示它时希望在表单中:

class Form
{
    protected $inputs = array();
    public function makeInput($type, $name)
    {
         echo '<input type="'.$type.'" name="'.$name.'">';
    }

    public function addInput($type, $name)
    {
         $this->inputs[] = array("type" => $type,
                "name" => $name);
    }

    public function run()
   {
       foreach($this->inputs as $array)
       { 
          $this->makeInput($array['type'], $array['name'];
       }
    }
}

$form = new form();

$this->addInput("text", "username");
$this->addInput("text", "password");

Or as someone else suggested, a person: 或者像其他人建议的那样,一个人:

class Person{

    public $name;
    public $job_title;
    // ... etc....

}

All are reasons to create classes as they represent something that has properties like a name or a job title, and may have methods, such as displaying a form. 所有这些都是创建类的原因,因为它们表示具有名称或作业标题等属性的东西,并且可能具有方法,例如显示表单。

基本上两者做同样的工作,但通过使用类,你可以更容易地管理你的代码,如果我们使用类,那么我们必须创建用于调用函数定义的对象,而如果我们直接创建函数,那么我们不需要创建对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM