何时在 PHP 中使用类与函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2122123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:08:01  来源:igfitidea点击:

When to use a Class vs. Function in PHP

phpfunctionclass

提问by jay

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. I'm thinking about calling the function 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?

假设我有一个用 php 构建的迷你日历小部件。我正在考虑调用函数miniCal('arrayVars1', 'var2')。但我可能会在那个页面上做两次。通过在此处使用类来使用更少的资源,创建它的新实例吗?

What tree should I be barking up here, because I feel like right now the tree is a brick wall...

我应该在这里吠什么树,因为我现在感觉这棵树是一堵砖墙......

采纳答案by Kaleb Brasee

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. 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).

类用于将数据表示为对象。如果您要表示诸如用户数据或拍卖出价之类的内容,则创建 User 对象或 AuctionBid 对象可以更轻松地将这些数据保存在一起,在您的代码中传递它,并使读者更容易理解。这些类将具有属性(数据字段,如数字、字符串或其他对象)以及方法(您可以对任何类进行操作的函数)。

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 guideand the Wikipedia OOP entry.

我建议您阅读PHP5 Object-Oriented Programming guideWikipedia OOP entry

回答by John Conde

A common thing to do since PHP5 was to create classes that act as libraries. This gives you the benefit of organizing your functionality and taking advantage of class features like __autoload();

自 PHP5 以来,通常要做的事情是创建充当库的类。这使您可以组织功能并利用 __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 (i.e. $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. 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.
  1. 您的加密功能被组合在一起并组织起来。您和任何维护代码的人都知道在哪里可以找到您的加密功能。
  2. 这是非常清晰易读的。有利于可维护性。
  3. 您可以使用 __autoload() 自动为您包含该类。这意味着您可以像使用内置函数一样使用它。
  4. 因为它包含在自己的类和自己的文件中,所以它是可重用的,并且可以轻松地移植到新项目中。

回答by Julian

Using classes is a good way for grouping your functions.

使用类是对函数进行分组的好方法。

The difference lies in the usage of the programming paradigm. Classes are necessary in O.O.P. but are not necessary in the Procedural paradigm. In the Procedural paradigm you can group functions in a file, which can be seen as a module.

不同之处在于编程范式的使用。类在 OOP 中是必需的,但在过程范式中不是必需的。在程序范式中,您可以将函数分组到一个文件中,该文件可以被视为一个模块。

--- 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. Classes are needed.

您可以使用OOP 范式。需要上课。

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). The Calculations object groups calculation functions, thus keeping them in one place.

范式的工作,但上面的 OOP 示例使用的是包含所有计算方法(函数)的 Calculations 对象。Calculations 对象对计算函数进行分组,从而将它们保存在一个地方。

The O.O.P. paradigm in this example obeys to a principles called "Solid responsibility". The idea behind this is to keep the code elegant, maintainable and readable.

本示例中的 OOP 范式遵循称为“可靠责任”的原则。这背后的想法是保持代码优雅、可维护和可读。

回答by John Doe

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. You can devise common naming conventions ("Encryption_Encrypt", "Encycryption_Decrypt", etc.)...but classes are just easier. If you only have 12 functions in your application, you could probably survive with only 1 or classes, if any.

如果您的应用程序中有 500 个函数,您可能希望将其中至少一半分组到更大的集合中以便于访问。您可以设计常见的命名约定(“Encryption_Encrypt”、“Encycryption_Decrypt”等)……但类更简单。如果您的应用程序中只有 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.

类还允许多态性,这很有帮助。如果你有几个非常相似的类,或者一个类的几个变体,你可以节省代码……而不必构造一些多用途的、类似弗兰肯斯坦的类。

回答by Tyler Carter

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_queryuses 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:

或者,也许您想构建一个表单,您可以创建一个包含输入列表的表单对象,这样当您决定显示它时,您希望位于表单内:

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.

所有这些都是创建类的原因,因为它们表示具有名称或职位等属性的内容,并且可能具有方法,例如显示表单。

回答by Priyank Dadhich

Basically Both Do same work but by using classes you can manage your code in easier way, One more thing if we use class then we have to create object for calling functions define in it, while if we create functions directly then we don't need to create object.

基本上两者都做同样的工作,但通过使用类,您可以更轻松地管理代码,另外一件事,如果我们使用类,那么我们必须创建用于调用其中定义的函数的对象,而如果我们直接创建函数,则不需要创建对象。