Reputation: 597
I want to get the name of the class Foo by a method I set in the class Foo. I can get the name of class Foo with debug_backtrace() below. Is there another way?
<?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
-- UPDATE -- My English is not good, I did not tell. I want to do something like the following. Please write your answer accordingly.
index.php
<h1>Hello World</h1>
/view|
|foo|index.php
| |menu.php
| |detail.php
|
|user|login.php
|register.php
I will get the file for the above directory path. The directory path and class name will be the same.
<?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
Upvotes: 0
Views: 60
Reputation: 51894
Use get_class to get the object's class name.
class a {};
print get_class(new a());
# prints a
Or, you can use the __CLASS__
constant within a class scope:
class Foo {
public function getClassName() {
return __CLASS__;
}
}
print (new Foo())->getClassName();
# prints Foo
Upvotes: 2
Reputation: 131
If I understand you clearly ...
You can use the following constant.
__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();
Upvotes: 0