PHP:一个类如何引用它自己的名字?

标签 php

在PHP中,类如何引用自己的名字?

例如,执行此操作的方法是什么样的?

Dog::sayOwnClassName();
//echos "Dog";

更新

我看到每个人都在说 get_class($this)。但那是不正确的。如果我正在创建 Dog 的实例,那将起作用。我问的是调用 Dog 类本身的方法。如果 Dog 扩展了 Mammal,那么在 Dog 类中调用 get_class($this) 将返回 'Mammal .'.

换句话说:

  • 我不是在问“Dog 类是什么类”,答案是“Dog 类是 Mammal 类的成员。”
  • 我也不是在问“给定狗类 Dog 的实例(称为 Rover),它的类是什么?”,答案是“狗”。
  • 我要问的是,“Dog 类本身可以告诉我‘我叫 Dog 吗?’”

例如:

class Mammal {    
  public function find_by_id($id){
    $query = "SELECT * FROM " . $myclass . " WHERE `id` = " . $id;
    //(etc)
    return $matching_object;
  }
}

class Dog extends Mammal {
//find_by_id method should know to do a SELECT from Dog table     
}

更新2

Yacoby 关于 get_called_class() 的建议是正确的。下面是它在我给出的示例中的工作原理。

class Mammal {    
      public function find_by_id($id){
        $myclass = get_called_class();
        $query = "SELECT * FROM " . $myclass . " WHERE `id` = " . $id;
        //(etc)
        return $matching_object;
      }
    }

    class Dog extends Mammal {
    //find_by_id knows to do a SELECT from Dog table
    //and will return the correct dog object     
    }

最佳答案

三个选项,get_called_class() , get_class()magic constant __CLASS__

这三个 get_called_class()是您在使用静态函数处理时想要的,尽管不幸的是它确实要求 PHP 版本至少为 5.3.0


get_called_class()

如果您需要在派生类时在静态函数中获取类,它会略有不同,因为 self 被解析为放置它的类名(参见 Limitations of self:: )。要解决此问题,您需要使用 PHP 5.3.0 中的函数 get_called_class() .

如果您不能使用 PHP 5.3.0 或更高版本,您可能会发现您无法使该函数成为静态函数并仍然让它达到您想要的结果。


获取类()

get_class() 返回对象实际类的名称,无论函数调用在何处。

class Animal{
     public function sayOwnClassName(){
         echo get_class($this);
     }
}

class Dog extends Animal{
}


$d = new Dog();
$d->sayOwnClassName(); //echos Dog

$a = new Animal();
$a->sayOwnClassName(); //echos Animal

get_class 也可以在没有参数的情况下使用,乍一看似乎表明它可以用于静态函数(因为不需要传递 $this) ,但是当不带参数使用时,它的工作方式与 __CLASS__

相同
class Animal{
     public static function sayOwnClassName(){
         echo get_class();
     }
}

class Dog extends Animal{
}


Dog::sayOwnClassName(); //echos Animal
Animal::sayOwnClassName(); //echos Animal

__类__

__CLASS__ 始终扩展为解析 __CLASS__ 的类的名称,即使考虑到继承也是如此。

class Animal{
     public function sayOwnClassName(){
         echo __CLASS__; //will always expand to Animal
     }
}

class Dog extends Animal{
}

$d = new Dog();
$d->sayOwnClassName(); //echos Animal

$a = new Animal();
$a->sayOwnClassName(); //echos Animal

关于PHP:一个类如何引用它自己的名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2594093/

相关文章:

php - Mysql中的Order By问题

php - 从 MySQL CSV 导出中排除列

php - while循环迭代一次进入foreach循环php mysql

将 URL 变量插入 mysql 数据库的 PHP 脚本?

php - 如何从 CodeIgniter 库中抛出异常

php - 如何将日期值插入 PostgreSQL 表中?

php - 执行 Composer 命令时错误 "' php' 未被识别为内部或外部命令、可运行程序或批处理文件”

php - 无法通过system()执行外部程序?

php - UrlGenerationException(缺少 [Route] 所需的参数)

php - jquery/mysql插入错误