• 회원가입
  • 로그인
  • 구글아이디로 로그인

[PHP-생코] PHP 7강 - 접근제어자 = 속성의 가시성(property visibility) ※ 캡슐화(encapsulation)

952  


접근 제어자 1 - 개념

 

접근제어자(access modifier) = 속성의 가시성(property visibility) 

캡슐화 달성 수단 중 하나.

 

캡슐화(encapsulation)

객체 사용자에게 필요한 정보/기능만 노출시켜서, 편의성 및 안정성 높이는 작업.

 

 

 

 

접근 제어자 2 (private vs public)


<?php

class MyFileObject{

  private $filename;

  function __construct($fname){

    $this->filename = $fname;

    if(!file_exists($this->filename)){

      die('There is no file '.$this->filename);

    }

  }

  function isFile(){

    return is_file($this->filename);

  }

}

$file = new MyFileObject('data.txt');

// $file = new MyFileObject();

// $file->filename = 'data.txt';

var_dump($file->isFile());

var_dump($file->filename);

?>

 

 

 

접근 제어자 3 - (private vs public)

 

<?php

class Person{

  private $name;

  function sayHi(){

    print("Hi, I'm {$this->name}.");

  }

  function setName($_name){

    if(empty($_name)){

      die('I need name');

    }

    $this->name = $_name;

  }

  function getName(){

    return $this->name;

  }

}

$egoing = new Person();

$egoing->setName('egoing');

$egoing->sayHi();

print($egoing->getName());

?>

 


접근 제어자 3 (method visibility)

 

<?php

class Person{

  private $name;

  public function sayHi(){

    print("Hi, I'm {$this->name}.");

  }

  public function setName($_name){

    $this->ifEmptyDie($_name);

    $this->name = $_name;

  }

  public function getName(){

    return $this->name;

  }

  private function ifEmptyDie($value){

    if(empty($value)){

      die('I need name');

    }

  }

}

$egoing = new Person();

$egoing->setName('egoing');

$egoing->sayHi();

print($egoing->getName());

?>

 

https://opentutorials.org/module/6/15730

 

PS.

 

Visibility 

https://www.php.net/manual/en/language.oop5.visibility.php

 

접근제어자

https://homzzang.com/b/php-1065

 

 


분류 제목
PHP-생코 PHP 28강 - 상속과 final
PHP-생코 PHP 27강 - 상속 (접근제어자 protected)
PHP-생코 PHP 26강 - 상속 (override와 parent)
PHP-생코 PHP 25강 - 컴포저 5 (autoload)
PHP-생코 PHP 24강 - 컴포저 4 (의존성)
PHP-생코 PHP 23강 - 컴포저 3 (기본 사용법)
PHP-생코 PHP 22강 - 컴포저 2 (설치)
PHP-생코 PHP 11강 - 컴포저
PHP-생코 PHP 10강 - 클래스로딩과 네임스페이스 (namespace) ※ require, include 응용.
PHP-생코 PHP 9강 - 클래스 맴버 만들기 (static)
PHP-생코 PHP 8강 - 상속 (inheritance) : extends 키워드
PHP-생코 PHP 7강 - 접근제어자 = 속성의 가시성(property visibility) ※ 캡슐화(encapsul…
PHP-생코 PHP 6강 - 생성자 (인스턴스 초기화) ★★★
PHP-생코 PHP 5강 - 인스턴스 변수
PHP-생코 PHP 4강 - 클래스・인스턴스(객체)・메서드 생성 ★★★
PHP-생코 PHP 3강 - 함수와 객체 비교 2 - 배열 제어 ★★
PHP-생코 PHP 2강 - 함수와 객체 비교 1 - 파일 제어
PHP-생코 PHP 1강 - 객체 지향 프로그래밍 의미
JAVA-생코 Java 25강 - 데이터타입 (2/2) : 데이터타입 비교
JAVA-생코 Java 24강 - 데이터타입 (1/2) : 데이터의 크기
31/35
목록
찾아주셔서 감사합니다. Since 2012