programing tip

PHP에서 클래스 이름을 어떻게 얻습니까?

itbloger 2020. 9. 14. 08:09
반응형

PHP에서 클래스 이름을 어떻게 얻습니까?


public class MyClass {

}

Java에서는 다음과 같이 클래스 이름을 얻을 수 있습니다. String className = MyClass.class.getSimpleName();

PHP에서 어떻게할까요? 나는 이미 알고 get_class()있지만 객체에 대해서만 작동합니다. 현재 저는 Active Record에서 일하고 있습니다. 나는 같은 진술이 필요합니다 MyClass::className.


PHP 5.5부터 ClassName :: class 를 통해 클래스 이름 확인을 사용할 수 있습니다 .

PHP5.5의 새로운 기능을 참조하십시오 .

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

클래스 메서드에서이 기능을 사용하려면 static :: class 사용하십시오 .

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

이전 버전의 PHP의 경우 get_class ()를 사용할 수 있습니다 .


__CLASS__클래스 내에서 사용 하여 이름을 얻을 수 있습니다 .

http://php.net/manual/en/language.constants.predefined.php


It sounds like you answered your own question. get_class will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class

Here is their example:

 <?php

 class foo 
 {
     function name()
     {
         echo "My name is " , get_class($this) , "\n";
     }
 }

 // create an object
 $bar = new foo();

 // external call
 echo "Its name is " , get_class($bar) , "\n"; // It's name is foo

 // internal call
 $bar->name(); // My name is foo

To make it more like your example you could do something like:

 <?php

 class MyClass
 {
       public static function getClass()
       {
            return get_class();
       }
 }

Now you can do:

 $className = MyClass::getClass();

This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.

<?php

class MyClass
{
    public static function getClass()
    {
        return get_called_class();
    }

    public static function getDefiningClass()
    {
        return get_class();
    }
}

class MyExtendedClass extends MyClass {}

$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'

Now, I have answer for my problem. Thanks to Brad for the link, I find the answer here. And thanks to J.Money for the idea. My solution:

<?php

class Model
{
    public static function getClassName() {
        return get_called_class();
    }
}

class Product extends Model {}

class User extends Model {}

echo Product::getClassName(); // "Product" 
echo User::getClassName(); // "User" 

To get class name you can use ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

It looks like ReflectionClass is a pretty productive option.

class MyClass {
    public function test() {
        // 'MyClass'
        return (new \ReflectionClass($this))->getShortName();
    }
}

Benchmark:

Method Name      Iterations    Average Time      Ops/second
--------------  ------------  --------------    -------------
testExplode   : [10,000    ] [0.0000020221710] [494,518.01547]
testSubstring : [10,000    ] [0.0000017177343] [582,162.19968]
testReflection: [10,000    ] [0.0000015984058] [625,623.34059]


<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5


end(preg_split("#(\\\\|\\/)#", Class_Name::class))

Class_Name::class: return the class with the namespace. So after you only need to create an array, then get the last value of the array.


echo substr(strrchr(__CLASS__, "\\"), 1);    

참고URL : https://stackoverflow.com/questions/15103810/how-do-i-get-class-name-in-php

반응형