我有一個對象的方法,有時我需要調用靜態,有時不需要。php,靜態方法重載
class MYOBJECT
{
private $group_id;
public function SetGroupId($_id) { $this->group_id = $_id; }
public static function GetGroupName($_id=NULL)
{
// is there any way to implement condition like this?
if(_called_as_static) $id = $_id;
else $id = $this->group_id;
$query mysql_query("SELECT name FROM group WHERE id = $id");
list($name) = mysql_fetch_array($query);
return $name;
}
}
$obj = new MYOBJECT;
$obj->SetGroupId(4);
// should work both ways
$name = $obj->GetGroupName();
$name = MYOBJECT::GetGroupName(4);
我解決這樣說:
public static function MYOBJECT::GetGroupName($_id=NULL)
{
if(is_object($_id)) $_id = $_id->GetGroupId();
...
}
$name = MYOBJECT:GetGroupName(4);
$name = $obj->GetGroupName($obj);
,但仍然是有什麼更優雅?
有這樣的切換方法是非常糟糕的做法。我建議只提交方法是靜態的或不是。 – deceze 2012-03-21 09:45:09
你可以嘗試if(isset($ this)){} – 2013-10-16 12:07:25