[英]A odd question php OOP
大家好。 我正在為一些數據設計一個 model,並希望它像這樣工作: $this->groupmodel->VARIABLE->FUNCTION(VAR1, VAR2);
調用 function,其中 VARIABLE 可以更改為任何內容,並傳遞給 function。
這感覺更正確(然后說$this->groupmodel->FUNCTION(VARIABLE, VAR1, VAR2)
),因為每個VARIABLE
具有完全相同的功能,並且這些功能正在(技術上)在VARIABLE
上執行。 這可能嗎?
請注意, VARIABLE
可以在任何地方設置(在它自己的 function 或在被調用的 function 中)(它在整個 class 中持續存在,但需要設置)。
最大限度
您應該創建一個 class 來實現您要使用的功能,並且您的所有“變量”都應該是該 class 的對象。 例如:
class Kid {
private $age = 0;
public function _construct($age){
$this->age = $age;
}
public function birthday() { // implement in Kid instead of in Groupmodel
$this->age++;
echo "Growing old... ";
}
public function age($age_new = null){ // age setter and getter
if(!is_null($age_new)){
$this->age = $age_new;
}
return $this->age;
}
}
然后在您的 groupmodel 中:
class GroupModel {
private $variables;
public function _set($name, $value) {
if (array_key_exists($name, $this->variables)) {
$this->variables[$name]->age($value);
} else {
$this->variables[$name] = new Kid($value);
}
}
public function _get($name) {
if (array_key_exists($name, $this->variables)) {
return $this->variables[$name];
} else {
return null;
}
}
}
所以你可以打電話:
$this->groupmodel = new GroupModel()
$this->groupmodel->var1 = 8
$this->groupmodel->var1->birthday(); // will add 1 to var1's age and print "Growing old"
$this->groupmodel->var1 = 9 // will replace var1's age
我們在這里所做的是在每次嘗試設置 GroupModel object 的屬性時自動創建 class Kid 的對象。 (這就是魔法方法 _set() 所做的)
事實上,它將它們創建為私有數組的元素,而不是 GroupModel 的真實屬性。
然后,當嘗試訪問這些“屬性”時,_get() 將被調用,它將檢索數組的元素並返回它。
由於它將是 class Kid 的 object,因此您可以調用它實現的每個方法(如生日())。
有關重載和魔術方法(如 _get 和 _set)的更多信息,請參閱:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
PHP 5.3 讓您使用非常好的東西,稱為后期 static 綁定
假設您有 2 個類:擴展 groupmodel 的 Foo:
class groupmodel {
const MY_CONST = 'groupmodel';
protected function myName(){
echo static::MY_CONST; //Will print 'groupmodel';
}
protected function whoAmI(){
//do something here
}
}
和福:
class Foo extends groupmodel {
const MY_CONST = 'ClassFoo';
public function tellMyName(){
$this->myName(); //Will print 'ClassFoo';
}
}
實際上,這個想法不是使用
$this->groupmodel->FUNCTION(VARIABLE, VAR1, VAR2)
OR
$this->groupmodel->VARIABLE->FUNCTION(VAR1, VAR2);
你將使用:
$object = new Foo();
$object->tellMyName(); //Will print 'ClassFoo'
現在 $object 將授予所有groupmodel方法。
與您的案例以及盡可能多地使用 OOP 一起工作的另一件重要事情是設置抽象 class
對的,這是可能的。 php 允許您對成員和 function 訪問使用變量。 例如: $this->groupmodel->$myvar->myfunc($var1, $var2);
這將調用$this->groupmodel->{Whatever-string-is-stored-in-myvar}
。
請注意,如果要執行此操作,必須在 class 中設置 groupmodel 並且 $myvar 必須是groupmodel
中的公共成員,並且 $myvar 的內容必須是有效成員,並且也是實現myfunc()
的 class 。 這是很多耦合依賴(因此 zerkms 貶低這種方法)。 不過,這將有助於了解您要做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.