I want to get a PHP class name without the use of namespace and without using reflection.

namespace CRMPiccoBundle\Services\RFC\Webhook;

class TicketCancelled extends Base implements Interface
{
    public function process() {
       // echo get_class()
    }
}

 Is there any simple way to get the class name without the namespace without using Reflection or the use of namespace?

php oop class 
2 Answers

By simply exploding the return from class_name and getting the last element:

 $class_parts = explode('\\', get_class());
 echo end($class_parts);

Or simply by removing the namespace from the output of get_class():

echo str_replace(__NAMESPACE__ . '\\', '', get_class());

works with or without namespace.

answered Dec 02


Php get class name without namespace from string

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

Php namespace class

<?php
	namespace m\name; // see "Defining Namespaces" section

	class MyClass {}
	function myfunction() {}
	const MYCONST = 1;

	$a = new MyClass;
	$c = new \my\name\MyClass; // see "Global Space" section

	$a = strlen('hi'); // see "Using namespaces: fallback to global
                   	// function/constant" section

	$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
                        	// constant" section
	$d = __NAMESPACE__ . '\MYCONST';
	echo constant($d); // see "Namespaces and dynamic language features" section
?>

Get class name from object PHP

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

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

Php get the class name of this

get_class($this);

Java get to class by string name

//get an according class variable
String className = "MyClass";
Class<?> cls = Class.forName(className);

//create instance of that class
Object myInstance = scl.newInstance();

answered Dec 30


Login and Submit Your Answer
Browse other questions tagged  php  oop  class or ask your own question.