簡體   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