php 什么是php中简单示例的封装?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/985298/
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 00:34:12  来源:igfitidea点击:

What is encapsulation with simple example in php?

phpencapsulation

提问by Jeremy Logan

What is encapsulation with simple example in php?

什么是php中简单示例的封装?

回答by Jeremy Logan

Encapsulation is just wrapping some data in an object. The term "encapsulation" is often used interchangeably with "information hiding". Wikipedia has a pretty thorough article.

封装只是将一些数据包装在一个对象中。术语“封装”通常与“信息隐藏”互换使用。维基百科有一篇非常详尽的文章

Here's an example from the first linkin a Google search for 'php encapsulation':

以下是Google 搜索 'php encapsulation' 中第一个链接的示例:

<?php

class App {
     private static $_user;

     public function User( ) {
          if( $this->_user == null ) {
               $this->_user = new User();
          }
          return $this->_user;
     }

}

class User {
     private $_name;

     public function __construct() {
          $this->_name = "Joseph Crawford Jr.";
     }

     public function GetName() {
          return $this->_name;
     }
}

$app = new App();

echo $app->User()->GetName();

?>

回答by Saman Shafigh

Encapsulation is protection mechanism for your class and data structure. It makes your life much easier. With Encapsulation you have a control to access and set class parameters and methods. You have a control to say which part is visible to outsiders and how one can set your objects parameters.

封装是类和数据结构的保护机制。它让你的生活更轻松。使用封装,您可以控制访问和设置类参数和方法。您可以通过控件说明哪些部分对外人可见,以及如何设置对象参数。

Access and sett class parameters

访问和设置类参数

(Good Way)

(好办法)

<?php

class User
{
    private $gender;

    public function getGender()
    {
        return $this->gender;
    }

    public function setGender($gender)
    {
        if ('male' !== $gender and 'female' !== $gender) {
            throw new \Exception('Set male or female for gender');
        }

        $this->gender = $gender;
    }
}

Now you can create an object from your User class and you can safely set gender parameters. If you set anything that is wrong for your class then it will throw and exception. You may think it is unnecessary but when your code grows you would love to see a meaningful exception message rather than awkward logical issue in the system with no exception.

现在您可以从您的 User 类创建一个对象,您可以安全地设置性别参数。如果你为你的班级设置了任何错误的东西,那么它就会抛出异常。您可能认为这是不必要的,但是当您的代码增长时,您希望看到有意义的异常消息,而不是系统中没有异常的尴尬逻辑问题。

$user = new User();
$user->setGender('male');

// An exception will throw and you can not set 'Y' to user gender
$user->setGender('Y');

(Bad Way)

(坏道)

If you do not follow Encapsulation roles then your code would be something like this. Very hard to maintain. Notice that we can set anything to the user gender property.

如果您不遵循封装角色,那么您的代码将是这样的。很难维护。请注意,我们可以为用户性别属性设置任何内容。

<?php

class User
{
    public $gender;
}

$user = new User();
$user->gender = 'male';

// No exception will throw and you can set 'Y' to user gender however 
// eventually you will face some logical issue in your system that is 
// very hard to detect
$user->gender = 'Y';

Access class methods

访问类方法

(Good Way)

(好办法)

<?php

class User
{
    public function doSomethingComplex()
    {
        $this->doThis(...);
        ...
        $this->doThat(...);
        ...
        $this->doThisExtra(...);
    }

    private function doThis(...some Parameters...)
    {
      ...
    }

    private function doThat(...some Parameters...)
    {
      ...
    }

    private function doThisExtra(...some Parameters...)
    {
      ...
    }
}

We all know that we should not make a function with 200 line of code instead we should break it to some individual function that breaks the code and improve the readability of code. Now with encapsulation you can get these functions to be private it means it is not accessible by outsiders and later when you want to modify a function you would be sooo happy when you see the private keyword.

我们都知道我们不应该用 200 行代码来制作一个函数,而是应该将它分解为一些单独的函数来破坏代码并提高代码的可读性。现在通过封装,您可以将这些函数设为私有,这意味着外部人员无法访问它,以后当您想要修改函数时,当您看到 private 关键字时,您会很高兴。

(Bad Way)

(坏道)

class User
{
    public function doSomethingComplex()
    {
        // do everything here
        ...
        ...
        ...
        ...
    }
}

回答by Offshore PHP Outsourcing India

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The wrapping up of data and methods into a single unit (called class) is known as encapsulation. The benefit of encapsulating is that it performs the task inside without making you worry.

封装是将代码和它操作的数据绑定在一起的机制,并保护两者免受外部干扰和误用。将数据和方法包装到一个单元(称为类)中称为封装。封装的好处是它在内部执行任务而不会让您担心。

回答by thomasrutter

Encapsulation is a way of storing an object or data as a property within another object, so that the outer object has full control over what how the internal data or object can be accessed.

封装是一种将对象或数据作为属性存储在另一个对象中的方法,以便外部对象可以完全控制如何访问内部数据或对象。

For example

例如

class OuterClass
{
  private var $innerobject;

  function increment()
  {
    return $this->innerobject->increment();
  }
}

You have an extra layer around the object that is encapsulated, which allows the outer object to control how the inner object may be accessed. This, in combination with making the inner object/property private, enables information hiding.

在被封装的对象周围有一个额外的层,它允许外部对象控制内部对象的访问方式。这与制作内部对象/属性相结合private,可以实现信息隐藏

回答by Graham Perkins

People seem to be mixing up details of object orientation with encapsulation, which is a much older and wider concept. An encapsulated data structure

人们似乎将面向对象的细节与封装混为一谈,这是一个更古老、更广泛的概念。封装的数据结构

  • can be passed around with a single reference, eg increment(myDate) rather than increment(year,month,day)
  • has a set of applicable operations stored in a single program unit (class, module, file etc)
  • does not allow any client to see or manipulate its sub-components EXCEPT by calling the applicable operations
  • 可以使用单个引用传递,例如 increment(myDate) 而不是 increment(year,month,day)
  • 在单个程序单元(类、模块、文件等)中存储了一组适用的操作
  • 不允许任何客户端通过调用适用的操作来查看或操作其子组件

You can do encapsulation in almost any language, and you gain huge benefits in terms of modularisation and maintainability.

您几乎可以使用任何语言进行封装,并且您在模块化和可维护性方面获得了巨大的好处。

回答by Neha Sinha

Wrappingup data member and method together into a single unit (i.e. Class) is called Encapsulation. Encapsulationis like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object. Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

数据成员和方法一起包装成一个单元(即类)称为封装封装就像封装在一个胶囊中。即将与对象相关的相关操作和数据封装到该对象中。封装就像你的包,你可以在里面放你的笔、书等。这意味着这是封装成员和功能的属性。

<?php
 class YourMarks
  {
   private $mark;
   public Marks
  {
   get { return $mark; }
   set { if ($mark > 0) $mark = 10; else $mark = 0; }
  }
  }
?>

I am giving an another example of real life(daily use) that is “TV operation”. Many peoples operate TV in daily life.

我再举一个现实生活(日常使用)的例子,就是“电视操作”。许多人在日常生活中操作电视。

It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel. Here everything is in private except remote so that anyone can access not to operate and change the things in TV.

它是用盖子封装的,我们可以远程操作,不需要打开电视和换频道。这里除了遥控器之外,一切都是私密的,这样任何人都可以访问而不是操作和更改电视中的东西。

回答by Saifullah khan

/* class that covers all ATM related operations */
class ATM {

    private $customerId;
    private $atmPinNumber;
    private $amount;

    // Verify ATM card user
    public function verifyCustomer($customerId, $atmPinNumber) {
        ... function body ...
    }

    // Withdraw Cash function
    public function withdrawCash($amount) {
        ... function body ...
    }

    // Retrieve mini statement of our account
    public function miniStatement() {
        ... function body ...
    }
}

In the above example, we have declared all the ATM class properties (variables) with private access modifiers. It simply means that ATM class properties are not directly accessible to the outer world end-user. So, the outer world end-user cannot change or update them directly.

在上面的示例中,我们使用私有访问修饰符声明了所有 ATM 类属性(变量)。它只是意味着外部世界的最终用户不能直接访问 ATM 类属性。因此,外部世界的最终用户无法直接更改或更新它们。

The only possible way to change a class property (data) is a method (function). That's why we have declared ATM class methods with public access modifier. The user can pass the required arguments to a class method to do a specific operation.

更改类属性(数据)的唯一可能方法是方法(函数)。这就是我们使用公共访问修饰符声明 ATM 类方法的原因。用户可以将所需的参数传递给类方法以执行特定操作。

It means users do not have whole implementation details for ATM class. It's simply known as data hiding.

这意味着用户没有 ATM 类的完整实现细节。它简称为数据隐藏。

Reference: http://www.thecreativedev.com/php-encapsulation-with-simple-example/

参考:http: //www.thecreativedev.com/php-encapsulation-with-simple-example/

回答by serono denis dayoh

Encapsulation is the process of hidding the data of the object from outside world and accessed to it is restricted to members of the class.

封装是将对象的数据从外界隐藏起来的过程,并且仅限于类的成员访问它。

回答by Qazi Ahmad

Encapsulation: - wrapping of data in single unit. also we can say hiding the information of essential details. Example: You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.

封装: - 在单个单元中包装数据。我们也可以说隐藏了重要细节的信息。 例子:你有一部手机....那里有一些界面可以帮助你与手机互动,你可以使用手机的服务。但实际上在手机中工作是隐藏的。你不知道它在内部是如何工作的。

回答by VVS

The opposite of encapsulation would be something like passing a variable to every method (like a file handle to every file-related method) or global variables.

封装的反面类似于将变量传递给每个方法(如每个文件相关方法的文件句柄)或全局变量。