How do I get class name in PHP?

后端 未结 10 1888
名媛妹妹
名媛妹妹 2020-11-29 04:37
public class MyClass {

}

In Java, we can get class name with String className = MyClass.class.getSimpleName();

How to do this

相关标签:
10条回答
  • 2020-11-29 05:03

    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]
    
    
    0 讨论(0)
  • 2020-11-29 05:03

    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
    
    0 讨论(0)
  • 2020-11-29 05:04

    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" 
    
    0 讨论(0)
  • 2020-11-29 05:04

    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.

    0 讨论(0)
提交回复
热议问题