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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题