PHPのOOPに関するチュートリアルに続き、__get()
の機能の仕組みを理解していません。ここでは、コードです:関数__get()はPHPで何の効果も与えていません
<?php
class Animal{
protected $name;
protected $favorite_food;
protected $sound;
protected $id;
public static $number_of_animals = 0;
const PI = "3.14159";
//function to return the name
//encapsulation
function getName(){
//when you want to refer attribute in a class
return $this->name;
}
//initialize things
function __construct(){
//generate random 100-10
$this->id = rand(1,10);
echo $this->id ." has been assigned<br/>";
//akses static attribute in a class
Animal::$number_of_animals++;
}
//destruct the object
function __destruct(){
echo $this->name ." is being destroyed :(";
}
//getter : to get protected attribute of a function
function __get($name){
echo "Asked for " . $name . "<br/>";
return $this->$name;
}
//setter : set the attribute to
function __set($name, $value){
switch($name){
case "name" :
$this->name = $value;
break;
case "favorite_food" :
$this->favorite_food = $value;
break;
case "sound" :
$this->sound = $value;
break;
default :
echo $name ."Name not found";
}
echo "Set " .$name. " to " .$value. "<br/>";
}
function run(){
echo $this->name. " runs<br/>";
}
}
class Dog extends Animal{
function run(){
echo $this->name. " runs like crazy<br/>";
}
}
$animal_one = new Animal();
$animal_one->name = " SPOT";
$animal_one->favorite_food = " MEAT";
$animal_one->sound = " RUFF";
echo $animal_one->name ." says". $animal_one->sound. " give me some " .$animal_one->favorite_food. " my id is " .$animal_one->id. " total animal is " .Animal::$number_of_animals. "<br/><br/>";
?>
出力は次のようになります。
5 has been assigned
Set name to SPOT
Set favorite_food to MEAT
Set sound to RUFF
Asked for name
Asked for sound
Asked for favorite_food
Asked for id
SPOT says RUFF give me some MEAT my id is 5 total animal is 1
SPOT is being destroyed :(
私は$sound
または$favorite_food
などの別の属性に__get()
機能では、引数と値を変更しようとすると、それが与えるものではありません出力への変更。出力は変わりません。私はそれをなぜ$name
に設定しなければならないのか分からない。
あなたの質問は何ですか?何を言おうと努力することはできません。何が効いていないのですか?値を任意の変数名に設定できます。どこでも '$ name'を使用する必要はありません。 O_o –
@JonStirling私の質問は、 '__get()'( 'not getName()')関数を見てください。なぜ '$ name'をセットしなければならないのですか?なぜ$ soundのような別の属性はありませんか?属性を変更しても、出力に変更はありません。どうして?私の場合、 '__get()'関数は実際どのように機能しますか? – bnrfly
'__get'呼び出しに渡されるパラメータは、アクセスしようとしているプロパティです。変数の名前は何でもかまいません。アクセスしようとしているプロパティの名前は引き続き含まれます。 –