【问题标题】:php: To get the name of a class by the method of another classphp:通过另一个类的方法来获取一个类的名字
【发布时间】:2018-10-23 08:42:07
【问题描述】:

我想通过我在类 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

【问题讨论】:

    标签: php classname


    【解决方案1】:

    使用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
    

    【讨论】:

    • get_class,Bar 类结果的名称。我试过了。
    • @jspcal 但在这种情况下,$this 是一个Bar 对象,因为Foo::index() 中的(new Bar())-&gt;test(),而不是OP 想要的Foo
    • 不想用参数,所以有这样的搜索。
    【解决方案2】:

    如果我明白你的话......

    您可以使用以下常量。 __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();
    

    【讨论】:

    • 感谢您的回答。我知道这些方法。它的目的是在不使用参数的情况下获取。
    猜你喜欢
    • 2014-08-29
    • 2018-12-24
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多