繁体   English   中英

php:通过另一个类的方法获取一个类的名称

[英]php: To get the name of a class by the method of another class

我想我在类Foo设置方法来获取类Foo的名字。 我可以使用下面的debug_backtrace()获得类Foo的名称。 还有另一种方法吗?

<?php

class Foo{

  public function index(){
      return (new Bar())->test();
  }  
}


class Bar{

    public function test(){
        $info = debug_backtrace();
        $info = array_column($info, 'class');
        $name = current(array_diff($info, array(__CLASS__)));
        return "'$name' class name";
    }
}


$foo = (new Foo())->index();
echo $foo; // 'Foo' class name

-更新-我没有说英语。 我想做类似以下的事情。 请相应地写下您的答案。

index.php
<h1>Hello World</h1>


/view|
     |foo|index.php
     |    |menu.php
     |    |detail.php
     |    
     |user|login.php
          |register.php

我将获得上述目录路径的文件。 目录路径和类名称将相同。

<?php
class Foo{

  public function index(){
      return (new Template())->view('index.php');
  }  
}


class User{

  public function index(){
      return (new Template())->view('login.php');
  }  
}


class Template{

    public function view($file_name){
        $info = debug_backtrace();
        $info = array_column($info, 'class');
        $name = current(array_diff($info, array(__CLASS__)));
        include("view/$name/$file_name");
    }
}


$foo = (new Foo())->index();

//Hello World

使用get_class获取对象的类名称。

class a {};
print get_class(new a());
# prints a

或者,您可以在类范围内使用__CLASS__常量:

class Foo {
    public function getClassName() {
        return __CLASS__;
    }
}

print (new Foo())->getClassName();
# prints Foo

如果我清楚地了解你...

您可以使用以下常量。 __CLASS__

 1 <?php
 2 class Foo{
 3   public function index(){
 4        return __CLASS__;
 5   }
 6 }
 7
 8 echo (new Foo())->index()."\n";

新更新:另一种方式:

 1 <?php
 2 class A
 3 {
 4         public $name=__CLASS__;
 5         public function get_name()
 6         {
 7             return $this->name;
 8         }
 9 }
10 class B
11 {
12         public $name=__CLASS__;
13         public function get_name()
14         {
15            return $this->name;
16         }
17 }
18
19 echo (new A)->get_name();
20 echo "\n";
21 echo (new B)->get_name();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM