これは、 C# 言語でプロパティを定義する方法です。
C# では、PHP とは異なり、クラス プロパティは単純な変数ではなく、値を設定または取得するときにアクセサー関数が呼び出されます。したがって、初期化後にプロパティが変更されないようにロックできます。PHPでは、関数名の後に括弧が続くことなく、そのような値を呼び出すことができないようです。そのためのPHPに同様の概念はありますか?
意味がわかりません。
しかし、ゲッターとセッターについて話している場合は、変数をプライベートとして宣言し、パブリック メソッドを作成して値を取得できます。
private $lol;
public getlol(){
return $this->lol;
}
しかし、定数について話している場合は、試してみる必要があります。
define("MAXSIZE", 100);
__get および __set マジック メソッドを使用して、PHP で get メソッドと set メソッドを使用することができます(ただし、実装は C# とは異なります)。
class A {
protected $test_int;
function __construct() {
$this->test_int = 2;
}
function __get($prop) {
if ($prop == 'test_int') {
echo 'test_int get method<br>';
return $this->test_int;
}
}
function __set($prop, $val) {
if ($prop == 'test_int') {
echo 'test_int set method<br>';
//$this->test_int = $val;
}
}
}
$obj = new A();
$obj->test_int = 3; //Will echo 'test_int set method'
echo $obj->test_int; //Will echo 'test_int get method' and then the value of test_int.
プロパティの値を「ロック」したい場合は、次のようにします。
function __set($prop, $val) {
if ($prop == 'test_int') {
//Do nothing
}
}