[PHP] 접근제어자

자식 클래스에서 부모 클래스를 상속 받는 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Class ParentClass {
    public $_public = "public";
    protected $_protected = "protected";
    private $_private = "private";

    function getPublic() {
        return $this->_public;
    }
    
    function getProtected() {
        return $this->_protected;
    }
    
    function getPrivate() {
        return $this->_private;
    }
}

Class ChildClass extends ParentClass {
    function getPublic() {
        return $this->_public;
    }
    
    function getProtected() {
        return $this->_protected;
    }
    
    function getPrivate() {
        return $this->_private;
    }
}

$obj = new ChildClass();

$obj->_public; // public
$obj->_protected; // Cannot access protected property
$obj->_private; // Undefined property
$obj->getPublic(); // public
$obj->getProtected(); // protected
$obj->getPrivate(); // Undefined property


자식 클래스에서 부모 클래스를 상속 받는 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Class ParentClass {
    public $_public = "public";
    protected $_protected = "protected";
    private $_private = "private";

    function getPublic() {
        return $this->_public;
    }
    
    function getProtected() {
        return $this->_protected;
    }
    
    function getPrivate() {
        return $this->_private;
    }
}

Class ChildClass extends ParentClass {
    function getPublic() {
        return $this->_public;
    }
    
    function getProtected() {
        return $this->_protected;
    }
    
    function getPrivate() {
        return $this->_private;
    }
}

$obj = new ChildClass();

$obj->_public; // public
$obj->_protected; // Cannot access protected property
$obj->_private; // Undefined property

$obj->getPublic(); // public
$obj->getProtected(); // protected
$obj->getPrivate(); // Undefined property


정리

  • public: 내/외부, 어디서든 Access 가능
  • protected: 같은 클래스 및 자식 클래스에서만 Access 가능 (인스턴스에는 접근 불가)
  • private: 같은 클래스에서만 Access 가능 (인스턴스에는 접근 불가)

Categories:

Updated:

Leave a comment