php - Class 지정

ouneno·2023년 9월 11일
0

PHP

목록 보기
2/8

php에서의 '$'기호는 변수를 정의하고 참조하는데 사용되는 기호 이다

학번이름전공
99001 제니퍼 건축학과
99002 로버츠 경제학과


1. Class 및 변수 선언하기

// Student 클래스 생성
class Student {
	private $_studentId; // private 학번
	private $_name; // private 학생명
	private $_major; // private 전공
}

접근제어자

  • php에서도 객체지향 프로그래밍이 도입되어 class를 사용할 수 있다.
    현업에서도 다양히 class를 사용하는 것을 볼 수 있었다.
    Java언어와 마찬가지로 접근제어자 사용이 가능하다.
  1. public - 객체를 통해 클래스 내/외부 접근 가능
  2. private - 클래스 내부에서만 접근 가능. 외부 접근 불가
  3. protected - 클래스 내부와 해당 클래스를 상속한 하위 클래스 내 접근 가능

2. set()/get() 생성

class Student {
	private $_studentId;
	private $_name;
	private $_major;
	public function setStudentId($studentId) {
		$this -> _studentId = $studentId;
	}
	public function getStudentId() {
  		return $this -> _studentId;
	}	
	public function setName($name) {
		$this -> _name = $name;
	}
	public function getName() {
		return $this -> _name;
	}
	public function setMajor($major) {
		$this -> _major = $major;
	}
	public function getMajor() {
		return $this -> _major;
	}
}

3. 뜯어보기

생소한 연산자로 헷갈렸다.
하나의 컬럼만 사용해서 자세히 뜯어보자.

  1. under-hyphen('_')?

private $_studentId;

under hyphen을 사용한 이유는 클래스 내부에서 변수를 생성했기 때문에 사용했다.

  1. set메서드이름(입력받을변수명);
    $this -> 변수명 -> 입력받을변수명;
    public function setStudentId($studentId) {
    	$this -> _studentId = $studentId;
    }
  1. get메서드이름();
    return $this -> 변수명;
public function getStudentId() {
  	return $this -> _studentId;
}	 
profile
지속적인 성장을 추구하는 새싹 개발자입니다🌱

0개의 댓글

관련 채용 정보