What is encapsulation with simple example in php?

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

What is encapsulation with simple example in php?

14条回答
  •  借酒劲吻你
    2020-12-08 03:09

    /* 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.

    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.

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

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

提交回复
热议问题