duangang79177 2012-03-21 09:33
浏览 186
已采纳

php,静态方法重载

I have an object with method that sometimes I need to call as static, sometimes not.

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);

I solved it this way:

public static function MYOBJECT::GetGroupName($_id=NULL)
{
  if( is_object($_id) ) $_id = $_id->GetGroupId();

  ...
}

$name = MYOBJECT:GetGroupName(4);
$name = $obj->GetGroupName($obj);

but still, is there something more elegant?

  • 写回答

2条回答 默认 最新

  • dpgjci27392 2012-03-21 10:10
    关注

    You should avoid use of static calls in general [article].

    And in this case, you are even making it worse, because you clearly expect two different behavior from same function. This is reason enough to have two separate functions. Besides, there is no "more elegant" way to do it. Only thing you can change there is to assume, that whenever function is called with a parameter, it is static. Other alternatives would either include reflections (which are slow) or debug_backtrace() (which is plain ugly).

    I can recommend for you to watch few of the lectures from "Clean Code Talks". Even if this does not convince you to change your style, it will give you a solid introduction in concepts like Dependency Injection and Unit Testing:

    Also, you really should stop using the old mysql_* functions as an API for access MySQL. They are more then 10 years old, not maintained anymore and community has begun the process of deprecation.

    You should take a hard look at the alternatives: PDO and MySQLi. They both provide ability to use prepared statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)