Home  >  Article  >  Backend Development  >  Note 016 get_class() function in PHP

Note 016 get_class() function in PHP

黄舟
黄舟Original
2016-12-26 10:10:001867browse

The function of

get_class() is to return the class name of the object.

Explanation

Usage:

string get_class ([ object $obj ] )

Return the class name corresponding to the obj object. If obj is not an object, then will return false.

Through this method, we can write some low-level related code much more easily.

Note: Since PHP 5, obj is optional if called within a method of an object.

Example

Example 1:

<?phpclass TestCase{    function getName()
    {        echo "My name is ", get_class($this), "\n";
    }
}// Create an object
$instance = new TestCase();
// External call
echo "Its name is ", get_class($instance), "\n";
// Internal call
$instance->getName();

The output result is: Its name is TestCase My name is TestCase

Example 2: Class with namespace

<?php
namespace TestNamespace;
class TestCase{    
function getName()
    {        
echo "My name is ", get_class($this), "\n";
    }
}
// Create an object
$instance = new TestCase();
// External call
echo "Its name is ", get_class($instance), "\n";
// Internal call
$instance->getName();

The output result is: Its name is TestNamespaceTestCase My name is TestNamespaceTestCase

Therefore, this method is also very useful if you want to get the namespace corresponding to this class.

Example 3: Ignore the obj parameter

<?phpnamespace TestNamespace;class TestParentCase{    function getName()
    {        echo "My name is ", get_class(), "\n";
    }
}class TestCase extends TestParentCase{    function getThisName()
    {        echo "My name is ", get_class(), "\n";
    }
}// Create an object$instance = new TestCase();

$instance->getName();
$instance->getThisName();

The output result is: My name is TestNamespaceTestParentCase My name is TestNamespaceTestCase

Pay attention to the difference in the returned results. After omitting the obj parameter, you get is the name of the class that defines it

If there are other situations that need attention, you are welcome to give feedback to Hy369, and I will add it to my blog in time.

The above is the content of the get_class() function in Note 016 PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn