드디어..!


PHP

상수 선언은 두가지가있음

옛날 부터있던 define 함수 사용, 5.3 부터 생긴 const 문법

const 이놈은 웃긴게 opcode 컴파일 타임이라.. 변수를 선언할수가 없어 ㅠ


아무튼 PHP 8.1 부터 readonly 프로퍼티됨

8.2 는 readonly 클래스







PHP 는 런타임 타입체커여서 ㄹㅇ 불변객체임


출력내용


object(Student)#1 (1) {
  ["name"]=>
  string(10) "name name~"
}

name name~



대충 readonly 프로퍼티는 못바꾼다는 내용


Fatal error: Uncaught Error: Cannot modify readonly property Student::$name in /in/vCsTC:10

Stack trace:

#0 /in/vCsTC(18): Student->setName('another name!')

#1 {main} thrown in /in/vCsTC on line 10



const 좀 런타임선언으로 바꿔주면 안되나 ㅠ


--------------------------------------------------

<?php
readonly class Student {
public string $name;

public function __construct($name){
$this->name=$name;
}

public function setName($name){
$this->name = $name;
}
}
$readOnlyObj = new Student('name name~');
define("immutableObj", $readOnlyObj);

var_dump(immutableObj);
echo immutableObj->name;
immutableObj->setName('another name!'); //read only 라서 에러남