What is encapsulation with simple example in php?

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

What is encapsulation with simple example in php?

14条回答
  •  情书的邮戳
    2020-12-08 02:58

    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)

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

    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)

    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.

    (Bad Way)

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

提交回复
热议问题