简体   繁体   English

你能帮助我更好地理解PHP类吗?

[英]Can you help me understand PHP Classes a little better?

I am kind of a slow learner I guess when it comes to coding, I have been learning PHP for a couple of years and I still don't understand Classes so it's time I put some effort in to at least understanding them a little better. 我是一个慢学习者,我想在编码方面,我已经学习PHP几年了,我仍然不理解课程,所以是时候我付出一些努力来至少更好地理解它们。

I use functions for everything. 我使用函数来做所有事情。 People often make comments to me on here that they can't believe I have a social network site and I don't use classes. 人们经常在这里给我发表评论说他们不相信我有一个社交网站而且我不使用课程。

I really do not understand the benefit of them can you explain the benefits besides it supposedly being easiar for multiple people to work on your code? 我真的不明白他们的好处你能解释一下这个好处,除了它可以让多个人轻松处理你的代码吗?

To me it seems like classes just complicate simple task 对我来说,似乎只是简单的任务使类复杂化

Simply (in fact, extremely simply), classes allow you to organize code in logical units as well as provide containers and templates for user-created objects. 简单地(实际上,非常简单),类允许您以逻辑单元组织代码,以及为用户创建的对象提供容器和模板。

Let's say you have a car... A car can has a capacity and people inside. 假设你有一辆车......一辆车可以容纳人,里面有人。

class Car {
    private $people = array();
    private $capacity;

    function __construct($capacity) { $this->capacity = $capacity; }

    function addPerson($name) {
        if(count($this->people) >= $this->capacity) {
            throw new Exception("Car is already at capacity");
        } else {
            $this->people[] = $name;
        }
    }
    function getPeople() { return $this->people; }
    function getCapacity() { return $this->capacity; }
}

Now, we can start using those cars: 现在,我们可以开始使用这些车:

$aliceCar = new Car(2);
$aliceCar->addPerson("Alice");

$bobCar = new Car(4);
$bobCar->addPerson("Bob");
$bobCar->addPerson("Jake");

I now have 2 cars (instances), which holds different data. 我现在有2辆汽车(实例),它们拥有不同的数据。

echo implode(',', $aliceCar->getPeople()); // Alice
echo $aliceCar->getCapacity(); // 2

echo implode(',', $bobCar->getPeople()); // Bob,Jake
echo $bobCar->getCapacity(); // 4

I might also want to have a van, which will have an additional property for doors: 我可能还想要一辆面包车,它将为门提供额外的属性:

class Van extends Car {
    private $num_doors;

    function __construct($capacity, $num_doors) {
        parent::__construct($capacity); // Call the parent constructor
        $this->num_doors = $num_doors;
    }

    function getNumDoors() { return $this->num_doors; }
}

Now let's use that van: 现在让我们使用那辆面包车:

$jakeVan = new Van(7, 5);

// Van is ALSO a Car
$jakeVan->addPerson("Ron"); //Jake is with Bob now, so his son is driving the Van
$jakeVan->addPerson("Valery") //Ron's girlfriend

echo implode(',', $jakeVan->getPeople()); // Ron,Valery
echo $jakeVan->getCapacity(); // 7
echo $jakeVan->getNumDoors(); // 5

Now maybe you can see how we could apply those concepts towards the creation of, for example, a DBTable and a User class. 现在也许您可以看到我们如何将这些概念应用于创建DBTableUser类。


In fact, it's hard to really start explaining why classes simplify one's life without getting into the concepts of Object Oriented Programming (abstraction, encapsulation, inheritance, polymorphism). 实际上,很难真正开始解释为什么类在不涉及面向对象编程(抽象,封装,继承,多态)的概念的情况下简化了一个人的生活。

I recommend you read the following book. 我建议你阅读以下书籍。 It will help you grasp the core concepts of OOP and help you understand why objects to really make your life easier. 它将帮助您掌握OOP的核心概念,并帮助您理解为什么对象真正让您的生活更轻松。 Without an understanding of those concepts, it's easy to dismiss classes as just another complication. 如果不理解这些概念,很容易将类视为另一个复杂问题。

PHP 5 Objects, Patterns, and Practice PHP 5对象,模式和实践

PHP 5 Objects, Patterns, and Practice http://ecx.images-amazon.com/images/I/51BF7MF03NL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg PHP 5对象,模式和实践http://ecx.images-amazon.com/images/I/51BF7MF03NL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

Available at Amazon.com 可在Amazon.com上获得

This is a huge topic and even the best answers from the best SOers could only hope to scratch the surface, but I'll give my two cents. 这是一个很大的话题,即使是最好的SOers的最佳答案也只能希望划清界面,但我会给出两分钱。

Classes are the foundation of OOP . 类是OOP的基础。 They are, in a very basic way, object blueprints. 它们以非常基本的方式呈现对象蓝图。 They afford many features to the programmer, including encapsulation and polymorphism. 它们为程序员提供了许多功能,包括封装和多态。

Encapsulation, inheritance, and polymorphism are very key aspects of OOP, so I'm going to focus on those for my example. 封装,继承和多态是OOP的关键方面,因此我将重点关注我的示例。 I'll write a structured (functions only) and then an OOP version of a code snippet and I hope you will understand the benefits. 我将编写一个结构化的(仅限函数),然后编写代码片段的OOP版本,我希望您能理解其中的好处。

First, the structured example 首先,结构化的例子

<?php

function speak( $person )
{
  switch( $person['type'] )
  {
    case 'adult':
      echo "Hello, my name is " . $person['name'];
      break;
    case 'child':
      echo "Goo goo ga ga";
      break;
    default:
      trigger_error( 'Unrecognized person type', E_USER_WARNING );
  }
}

$adult = array(
    'type' => 'adult'
  , 'name' => 'John'
);
$baby = array(
    'type' => 'baby'
  , 'name' => 'Emma'
);

speak( $adult );
speak( $baby );

And now, the OOP example 而现在,OOP的例子

abstract class Person
{
  protected $name;

  public function __construct( $name )
  {
    $this->name = $name;
  }
  abstract public function speak();
}

class Adult extends Person
{
  public function speak()
  {
    echo "Hello, my name is " . $this->name;
  }
}

class Baby extends Person
{
  public function speak()
  {
    echo "Goo goo ga ga";
  }
}

$adult = new Adult( 'John' );
$baby  = new Baby( 'Emma' );

$adult->speak();
$baby->speak();

Not only should it be evident that just creating new data structures (objects) is easier and more controlled, pay attention to the logic in the speak() function in the first example, to the speak() methods in the 2nd. 不仅应该明确只是创建新的数据结构(对象)更容易和更有控制,请注意第一个示例中的speak()函数中的逻辑,以及第二个中的speak()方法。

Notice how the first one must explicitly check the type of person before it can act? 注意第一个人在行动之前必须如何明确检查人的类型? What happens when you add other action functions, like walk(), sit(), or whatever else you might have for your data? 添加其他操作函数时会发生什么,例如walk(),sit()或您可能拥有的其他任何数据? Each of those functions will have to duplicate the "type" check to make sure they execute correctly. 这些函数中的每一个都必须复制“类型”检查以确保它们正确执行。 This is the opposite of encapsulation. 封装相反 The data and the functions which use/modify them are not connected in any explicit way. 使用/修改它们的数据和功能没有以任何明确的方式连接。

Whereas with the OOP example, the correct speak() method is invoked based on how the object was created. 而使用OOP示例,根据对象的创建方式调用正确的speak()方法。 This is inheritance/polymorphism in action. 这是行动中的继承/多态。 And notice how speak() in this example, being a method of the object, is explicitly connected to the data it's acting upon? 并注意在这个例子中,speak()是一个对象的方法,它是如何明确地连接到它所作用的数据上的?

You are stepping into a big world, and I wish you luck with your learning. 你正在踏入一个大世界,祝你学习愉快。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。

In some ways, you are correct. 在某些方面,你是对的。 Classes can complicate simple tasks, and there certainly is a lot you can accomplish without using them. 可以使简单的任务复杂化,并且在不使用它们的情况下确实可以实现很多。 However, classes also make life a lot easier. 但是,课程也让生活变得更轻松。

Imagine your life without functions. 想象一下你的生活没有任何功能。 You would have to use GoTo statements to group together blocks of code. 您必须使用GoTo语句将代码块组合在一起。 Yuck. 呸。 Sure, you could accomplish the same things, but you would need to work a lot harder and it would be a lot more difficult for you to share your work with others. 当然,你可以完成同样的事情,但是你需要更加努力工作,而且与其他人分享你的工作将会困难得多。

Classes provide a neat way to group together blocks of similar code. 类提供了一种将类似代码块组合在一起的简洁方法。 Also, they allow you to capture and work with state very easily. 此外,它们允许您非常轻松地捕获和处理状态。

A good definition of a class is a blueprint to create objects. 类的良好定义是创建对象的蓝图。

Probably the single best thing you can do for yourself is to buy/find/borrow a book on Object Oriented Programming. 您可以为自己做的最好的事情就是购买/查找/借阅面向对象编程的书。 PHP classes are fundamentally the same as other modern languages (Java, C#, etc.), and once you learn OOP you will understand classes at a level of programming that is completely language-agnostic and can be applied to any OOP project, PHP or otherwise. PHP类基本上与其他现代语言(Java,C#等)相同,一旦你学习了OOP,你就会理解一个完全与语言无关的编程水平的类,并且可以应用于任何OOP项目,PHP或者除此以外。

With classes you can do something like 有了课程,你可以做类似的事情

class Stack {
  private $theStack = array();

  // push item onto the stack
  public function push(item) { ... }

  // get the top item from the stack
  public function pop() { ... } 
}

This simple example has some benefits. 这个简单的例子有一些好处。

  1. Code outside the class cannot manipulate the array that is used to implement the stack 类外部的代码无法操纵用于实现堆栈的数组
  2. The global namespace is not be polluted with unrelated variables 全局命名空间不会被不相关的变量污染
  3. Code that needs to use a stack can simply create an instance of the class (ie $myStack = new Stack()) 需要使用堆栈的代码可以简单地创建类的实例(即$ myStack = new Stack())

A class is like a calculator. 课程就像一个计算器。 You can have ten thousand different calculators that do the same thing, and each of them keep track of their own values and data. 你可以有一万个不同的计算器做同样的事情,每个计算器都跟踪他们自己的价值观和数据。

$cal1 = new calculator;
$cal2 = new calculator;

$cal1->add(5);
$cal2->add(3);

echo $cal1->show(); // returns 5

echo $cal2->show(); //returns 3

Every single calculator can do the same tasks, and run on the same code, but they all contain different values. 每个计算器都可以执行相同的任务,并运行相同的代码,但它们都包含不同的值。

If you were not using classes, you would have to individually create each calculator, assign it a variable, and copy and paste for every calculator you wanted to use at once. 如果您没有使用类,则必须单独创建每个计算器,为其分配变量,并复制并粘贴您想要一次使用的每个计算器。

function add_calc_1();
function add_calc_2();
function add_calc_3();
function subtract_calc_1();
function subtract_calc_2();
function subtract_calc_3();
function multiply_calc_1();
function multiply_calc_2();
function multiply_calc_3();
function divide_calc_1();
function divide_calc_2();
function divide_calc_3();

$total_1;
$total_2;
$total_3;

Instead, you can define a single class that is the code for a calculator, and then you can create as many different ones as you want, each with their own counters. 相反,您可以定义一个单独的类,它是计算器的代码,然后您可以根据需要创建任意多个不同的类,每个类都有自己的计数器。

class calc
{
   public $total;
   function add();
   function subtract();
   function multiply();
   function divide();
}
$cal1=new calc;
$cal2=new calc;
$cal3=new calc;

I use classes for my database tables. 我为我的数据库表使用类。

for Example we have 例如我们有

Id, firstname, lastname Id,名字,姓氏

For this i will use a class 为此,我将使用一个班级

class user{

    public $Id, $name, $lastname

    public function user($iId){

      Id = $iId;
      firstname = mysql_get('firstname');
      lastname = mysql_get('lastname');
}

for performance il use getData_functions to retrieve the data rather than putting them in the constructor. 对于性能,使用getData_functions来检索数据而不是将它们放在构造函数中。 Note the above is just a major idea rather than example of how to structure your classes 请注意,上面只是一个主要的想法,而不是如何构建类的示例

But later you can do this for multiple users 但是稍后您可以为多个用户执行此操作

while(mysql_get('Id')){

    $user = new user('Id');
    $print $user->firstname . " " . $user->lastname;
}

they make life easier. 他们让生活更轻松。

But i will more importantly that making life easier dosent mean its faster.. Because a badly designed class can slow things down. 但更重要的是,让生活更轻松,意味着更快......因为设计糟糕的课程可以减慢速度。

However for such function that are generic to my global program i dont use classes for them. 但是对于我的全局程序通用的这种功能,我不使用它们的类。

As a jokey anecdote, I once described PHP scripting without classes as like soap operas -- flat, and difficult to reuse in real-life situations. 作为一个jokey轶事,我曾经描述过没有类的PHP脚本,就像肥皂剧那样平坦,并且难以在现实生活中重复使用。 On the other hand, OO-PHP is a bit more like real drama; 另一方面,OO-PHP有点像真正的戏剧; objects are dynamic, and can be multi-faceted, and while there tends to be variation between their instantiations, they are often based on fundamental dramatic archetypes. 对象是动态的,并且可以是多方面的,虽然它们的实例化之间往往存在差异,但它们通常基于基本的戏剧性原型。

Basically what I'm saying is that it's easier to repurpose and reuse object-oriented code, which makes implementing open-source frameworks and utilities easier. 基本上我所说的是,重新利用和重用面向对象的代码更容易,这使得实现开源框架和实用程序更加容易。 I find pure scripting in PHP to be extremely difficult to maintain and reuse, and tends to allow for bad security holes that there are a lot of good, preexisting object-oriented utilities for. 我发现在PHP中使用纯脚本非常难以维护和重用,并且往往会导致很多安全漏洞,因为有很多好的,预先存在的面向对象的实用程序。

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

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