What is encapsulation with simple example in php?

前端 未结 14 1461
谎友^
谎友^ 2020-12-08 02:27

What is encapsulation with simple example in php?

14条回答
  •  北海茫月
    2020-12-08 02:57

    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-

    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();
    

提交回复
热议问题