我有一組變量,我需要多個其他類。我擴展了一個'漂亮'的getter函數(它猜測var的名字並且隨時產生'set'/'get'函數)來與setters一起工作。(php)變量類
實施例:
在接口/父母/不管:public $name;
在加載 'mySetterGetter' 類一些其他類:$set_get = new mySetterGetter(); $set_get->get_name();
。
不幸的是我不能在一個接口中使用變量,並且不能使用多個父類來擴展一個類。有沒有其他方法來加載這些「接口」/擴展Set/Get類?
我需要做的是以下幾點:
// This should be my "interface" one
class myIntegerInterface
{
public $one;
public $two;
public $three;
}
// This should be my "interface" two
class myStringInterface
{
public $foo;
public $bar;
public $whatever;
}
// This is my setter/getter class/function, that needs to extend/implement different variable classes
class mySetterGetter implements myIntegerInterface, myStringInterface
{
/**
* Magic getter/setter method
* Guesses for a class variable & calls/fills it or throws an exception.
* Note: Already defined methods override this method.
*
* Original @author Miles Keaton <[email protected]>
* on {@link http://www.php.net/manual/de/language.oop5.overloading.php#48440}
* The function was extended to also allow 'set' tasks/calls.
*
* @param (string) $val | Name of the property
* @param unknown_type $x | arguments the function can take
*/
function __call($val, $x)
{
$_get = false;
// See if we're calling a getter method & try to guess the variable requested
if(substr($val, 0, 4) == 'get_')
{
$_get = true;
$varname = substr($val, 4);
}
elseif(substr($val, 0, 3) == 'get')
{
$_get = true;
$varname = substr($val, 3);
}
// See if we're calling a setter method & try to guess the variable requested
if(substr($val, 0, 4) == 'set_')
{
$varname = substr($val, 4);
}
elseif(substr($val, 0, 3) == 'set')
{
$varname = substr($val, 3);
}
if (! isset($varname))
return new Exception("The method {$val} doesn't exist");
// Now see if that variable exists:
foreach($this as $class_var => $class_var_value)
{
if (strtolower($class_var) == strtolower($varname))
{
// GET
if ($_get)
{
return $this->class_var_value;
}
// SET
else
{
return $this->class_var_value = $x;
}
}
}
return false;
}
}
我想知道,你爲什麼需要那種魔法?爲什麼不直接通過屬性工作,如果需要自定義setter和getters,在後面的階段引入__get和__set? – phant0m
整個構建體實施得更大一些。我有一個加載器/擴展器類,數據庫處理,等等。整個構造當前被設置爲處理不同的場景(創建一個頁面,一個可拖動的框,一個表格和表單域,唯一的不同是a)我需要的基本值和b)我爲不同場景調用的構造函數類。因此,如果不爲不同的szenarios編寫set_/get_函數,我的生活將變得更加容易,但是讓__call方法處理這個函數,並且只在單個包裝文件/類中定義變量。 – kaiser