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

时间:2022-09-06 21:36:57

What is encapsulation with simple example in php?

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

14 个解决方案

#1


34  

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

封装只是将一些数据包装在一个对象中。术语“封装”通常与“信息隐藏”互换使用。*有一篇很好的文章。

Here's an example from the first link in 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();

?>

#2


10  

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.

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

#3


6  

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.

在封装的对象周围有一个额外的层,它允许外部对象控制如何访问内部对象。这与内部对象/属性私有化相结合,可以隐藏信息。

#4


6  

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.

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

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.

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

<?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行代码来创建一个函数,而应该将它分解为一些破坏代码并提高代码可读性的单个函数。现在使用封装,您可以将这些功能设置为私有,这意味着外部人员无法访问它们,以后当您想要修改某个功能时,当您看到私有关键字时,您会非常高兴。

(Bad Way)

(糟糕的方式)

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

#5


5  

encapsulation : Encapsulation is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation.

封装:封装是在单个模块中封装或绑定相关数据成员和方法的概念,称为封装。

here is the proper example of encapsulation

这是封装的正确例子

<?php
class person {
    public $name;
    public $age;
    function __construct($n, $a) {
        $this -> name = $n;
        $this -> age = $a;
    }
    public function setAge($ag) {
        $this -> ag = $ag;
    }
    public function display() {
        echo "welcome " . $this -> name . "<br/>";
        return $this -> age - $this -> ag;
    }
}
$person = new person("Pankaj", 25);
$person -> setAge(10);
echo "You are " . $person -> display() . " years old";
?>

#6


3  

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)
  • 可以通过单个引用传递,例如增量(myDate)而不是增量(年,月,日)
  • 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
  • 通过调用适用的操作,不允许任何客户端查看或操作其子组件

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

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

#7


2  

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.

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

#8


2  

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.

封装是从外部世界隐藏对象数据的过程,访问它的过程仅限于类的成员。

#9


2  

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.

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

#10


1  

Simply I prefer that is visibility of your class's property and method. For example- - public - private - protected

我只是希望能看到你班级的财产和方法。例如 - 公共 - 私人 - 受保护

Let's take a look real life example for encapsulation.

让我们来看看封装的真实例子。

 class MyClass{
    private $name;

    public function showName($newName){
        $this->name = $newName;
        return $this->name;
    }
 }


 //instantiate object

 $obj = new MyClass();
 echo $obj->showName("tisuchi");

In this case, encapsulation means, we restrict some properties. Like, name property, we can not access from outside of the class. On the other hand, we can access public function entitled showName() with one private parameter.

在这种情况下,封装意味着我们限制了一些属性。就像名称属性一样,我们无法从类外部访问。另一方面,我们可以使用一个私有参数访问名为showName()的公共函数。

Simply what I prefer of encapsulation is-

我更喜欢封装的是 -

visibility of your property and method.

Although, if you have any intension to understand encapsulation further, I refer to my special tutorial based on encapsulation.

虽然,如果您有任何意图进一步理解封装,我会参考基于封装的特殊教程。

http://tisuchi.com/object-oriented-php-part-3-encapsulation-php/

http://tisuchi.com/object-oriented-php-part-3-encapsulation-php/

Hope, it will make your concept more clear. Have fun!

希望,它会使您的概念更加清晰。玩的开心!

#11


1  

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation. Encapsulation is 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.

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

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

它采用封面封装,可以远程操作,无需打开电视和更换频道。这里的一切都是私密的,除了遥控器,所以任何人都可以访问不操作和改变电视中的东西。

#12


1  

/* class that covers all atm related opetation */
class ATM {

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

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

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

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

In the above example, we have declared all the ATM class property (variable) with private access modifier. It simply means that ATM class property is not directly accessible to the outer world end-user. So, the outer world end-user cannot change or update class property directly.

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

The only possible way to change the class property (data) was a method (function). That’s why we have declared ATM class methods with public access modifier. The user can pass 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/

#13


0  

In basic terms, it’s the way we define the visibility of our properties and methods. When you’re creating classes, you have to ask yourself what properties and methods can be accessed outside of the class. Let’s say we had a property named foo. If a class extends your class, is it allowed to manipulate and access foo? What if someone creates an instances of your class? Are they allowed to manipulate and access foo?

在基本术语中,它是我们定义属性和方法的可见性的方式。在创建类时,您必须问自己在类之外可以访问哪些属性和方法。假设我们有一个名为foo的属性。如果一个类扩展了你的类,是否允许操作和访问foo?如果有人创建了您的课程实例怎么办?他们被允许操纵和访问f​​oo吗?

#14


0  

Encapsulation is just how you wanted your objects/methods or properties/variables to be visible in your application. for example, :

封装就是您希望在应用程序中显示对象/方法或属性/变量的方式。例如, :

class ecap {

public $name;

private $id;

protected $tax;

}

If you want to access private or protected properties, then you have to use getter and setter methods in your class that will be accessible from outside of your class. Meaning, you cannot access your private or protected properties directly from outside of your class but you can use through any methods. Let’s take a look-

如果要访问私有或受保护的属性,则必须在类中使用可从类外部访问的getter和setter方法。这意味着,您无法直接从类外部访问私有或受保护的属性,但您可以通过任何方法使用。让我们来看看-

in the class, add the following method:

在类中,添加以下方法:

class ecap 
{
 public function userId(){
 return $this->id;
 }
} 

and we can access it like:

我们可以像访问它一样访问它:

 $obj = new ecap();
 echo $obj->userId();

#1


34  

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

封装只是将一些数据包装在一个对象中。术语“封装”通常与“信息隐藏”互换使用。*有一篇很好的文章。

Here's an example from the first link in 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();

?>

#2


10  

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.

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

#3


6  

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.

在封装的对象周围有一个额外的层,它允许外部对象控制如何访问内部对象。这与内部对象/属性私有化相结合,可以隐藏信息。

#4


6  

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.

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

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.

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

<?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行代码来创建一个函数,而应该将它分解为一些破坏代码并提高代码可读性的单个函数。现在使用封装,您可以将这些功能设置为私有,这意味着外部人员无法访问它们,以后当您想要修改某个功能时,当您看到私有关键字时,您会非常高兴。

(Bad Way)

(糟糕的方式)

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

#5


5  

encapsulation : Encapsulation is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation.

封装:封装是在单个模块中封装或绑定相关数据成员和方法的概念,称为封装。

here is the proper example of encapsulation

这是封装的正确例子

<?php
class person {
    public $name;
    public $age;
    function __construct($n, $a) {
        $this -> name = $n;
        $this -> age = $a;
    }
    public function setAge($ag) {
        $this -> ag = $ag;
    }
    public function display() {
        echo "welcome " . $this -> name . "<br/>";
        return $this -> age - $this -> ag;
    }
}
$person = new person("Pankaj", 25);
$person -> setAge(10);
echo "You are " . $person -> display() . " years old";
?>

#6


3  

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)
  • 可以通过单个引用传递,例如增量(myDate)而不是增量(年,月,日)
  • 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
  • 通过调用适用的操作,不允许任何客户端查看或操作其子组件

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

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

#7


2  

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.

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

#8


2  

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.

封装是从外部世界隐藏对象数据的过程,访问它的过程仅限于类的成员。

#9


2  

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.

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

#10


1  

Simply I prefer that is visibility of your class's property and method. For example- - public - private - protected

我只是希望能看到你班级的财产和方法。例如 - 公共 - 私人 - 受保护

Let's take a look real life example for encapsulation.

让我们来看看封装的真实例子。

 class MyClass{
    private $name;

    public function showName($newName){
        $this->name = $newName;
        return $this->name;
    }
 }


 //instantiate object

 $obj = new MyClass();
 echo $obj->showName("tisuchi");

In this case, encapsulation means, we restrict some properties. Like, name property, we can not access from outside of the class. On the other hand, we can access public function entitled showName() with one private parameter.

在这种情况下,封装意味着我们限制了一些属性。就像名称属性一样,我们无法从类外部访问。另一方面,我们可以使用一个私有参数访问名为showName()的公共函数。

Simply what I prefer of encapsulation is-

我更喜欢封装的是 -

visibility of your property and method.

Although, if you have any intension to understand encapsulation further, I refer to my special tutorial based on encapsulation.

虽然,如果您有任何意图进一步理解封装,我会参考基于封装的特殊教程。

http://tisuchi.com/object-oriented-php-part-3-encapsulation-php/

http://tisuchi.com/object-oriented-php-part-3-encapsulation-php/

Hope, it will make your concept more clear. Have fun!

希望,它会使您的概念更加清晰。玩的开心!

#11


1  

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation. Encapsulation is 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.

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

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

它采用封面封装,可以远程操作,无需打开电视和更换频道。这里的一切都是私密的,除了遥控器,所以任何人都可以访问不操作和改变电视中的东西。

#12


1  

/* class that covers all atm related opetation */
class ATM {

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

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

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

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

In the above example, we have declared all the ATM class property (variable) with private access modifier. It simply means that ATM class property is not directly accessible to the outer world end-user. So, the outer world end-user cannot change or update class property directly.

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

The only possible way to change the class property (data) was a method (function). That’s why we have declared ATM class methods with public access modifier. The user can pass 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/

#13


0  

In basic terms, it’s the way we define the visibility of our properties and methods. When you’re creating classes, you have to ask yourself what properties and methods can be accessed outside of the class. Let’s say we had a property named foo. If a class extends your class, is it allowed to manipulate and access foo? What if someone creates an instances of your class? Are they allowed to manipulate and access foo?

在基本术语中,它是我们定义属性和方法的可见性的方式。在创建类时,您必须问自己在类之外可以访问哪些属性和方法。假设我们有一个名为foo的属性。如果一个类扩展了你的类,是否允许操作和访问foo?如果有人创建了您的课程实例怎么办?他们被允许操纵和访问f​​oo吗?

#14


0  

Encapsulation is just how you wanted your objects/methods or properties/variables to be visible in your application. for example, :

封装就是您希望在应用程序中显示对象/方法或属性/变量的方式。例如, :

class ecap {

public $name;

private $id;

protected $tax;

}

If you want to access private or protected properties, then you have to use getter and setter methods in your class that will be accessible from outside of your class. Meaning, you cannot access your private or protected properties directly from outside of your class but you can use through any methods. Let’s take a look-

如果要访问私有或受保护的属性,则必须在类中使用可从类外部访问的getter和setter方法。这意味着,您无法直接从类外部访问私有或受保护的属性,但您可以通过任何方法使用。让我们来看看-

in the class, add the following method:

在类中,添加以下方法:

class ecap 
{
 public function userId(){
 return $this->id;
 }
} 

and we can access it like:

我们可以像访问它一样访问它:

 $obj = new ecap();
 echo $obj->userId();