ReflectionClass usage: Get all properties or methods of a Class in PHP

ReflectionClass class in PHP is a way to inspect a class and get all information of the class like what is its name, what are its properties, what are its methods, attributes, constants, even doc comments, interfaces, modifiers, namespaces, parent class, static properties, trait, check if the class is abstract or interfaces, check if iterable, etc. So today we use a simple example class and get all properties of that class.

Let’s create a class called image.php which contains $image and $height properties and multiple methods which contain the following code:

<?php

class Image
{
    public int $width;
    public int $height;

    /**
     * Constructor
     *
     * @param string $file
     *
     */
    public function __construct(string $file)
    {
        if (!extension_loaded('gd')) {
            exit('Error: PHP GD is not installed!');
        }
        if (is_file($file)) {
            $this->file = $file;
            $info = getimagesize($file);
            $this->width = $info[0];
            $this->height = $info[1];
            $this->bits = isset($info['bits']) ? $info['bits'] : '';
            $this->mime = isset($info['mime']) ? $info['mime'] : '';

            if ($this->mime == 'image/gif') {
                $this->image = imagecreatefromgif($file);
            } elseif ($this->mime == 'image/png') {
                $this->image = imagecreatefrompng($file);
            } elseif ($this->mime == 'image/jpeg') {
                $this->image = imagecreatefromjpeg($file);
            } elseif ($this->mime == 'image/webp') {
                $this->image = imagecreatefromwebp($file);
            }
        } else {
            throw new \Exception('Error: Could not load image ' . $file . '!');
        }
    }

    /**
     *
     *
     * @return    int
     */
    public function getWidth(): int
    {
        return $this->width;
    }

    /**
     *
     *
     * @return    int
     */
    public function getHeight(): int
    {
        return $this->height;
    }
}

Get all properties names of a Class in PHP

Now let’s create another index.php and add the following code:

<?php

require "Image.php";

$image ="webocreation.png";
$image = new Image($image);

$ReflectionClass = new \ReflectionClass('Image');
$imageproperties = $ReflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC);

echo "<pre>";
print_r($imageproperties);
echo "<pre>";

$imagemethods = $ReflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC);

echo "<pre>";
print_r($imagemethods);
echo "<pre>";

ReflectionProperty::IS_PUBLIC is to get only Public properties and ReflectionMethod::IS_PUBLIC is to get only Public methods.

Once you run the index.php you will see the output below where you can see the public property and public method:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => width
            [class] => Image
        )

    [1] => ReflectionProperty Object
        (
            [name] => height
            [class] => Image
        )

)

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => __construct
            [class] => Image
        )

    [1] => ReflectionMethod Object
        (
            [name] => getWidth
            [class] => Image
        )

    [2] => ReflectionMethod Object
        (
            [name] => getHeight
            [class] => Image
        )

)

In this way, you can get all the Methods and Properties of a class.

Get all methods names of a Class in PHP

Here is one Livewire Laravel example which shows how the ReflectionClass is used:

https://github.com/livewire/livewire/blob/master/src/ComponentConcerns/HandlesActions.php#L154-L167

protected function methodIsPublicAndNotDefinedOnBaseClass($methodName)
{
    return collect((new \ReflectionClass($this))->getMethods(\ReflectionMethod::IS_PUBLIC))
        ->reject(function ($method) {
            // The "render" method is a special case. This method might be called by event listeners or other ways.
            if ($method === 'render') {
                return false;
            }

            return $method->class === self::class;
        })
        ->pluck('name')
        ->search($methodName) !== false;
}

In this way, ReflectionClass is used to get all properties or methods of a Class in PHP. Please let us know if you have any questions or comments so that we can add extra topics. You can follow us at our Twitter account @rupaknpl, subscribe to our YouTube channel for opencart tutorials, and click to see all PHP development.

Previous article10 Tips for a smooth replacement Software rollout
Next articleWill Web3 Change How We Do E-Commerce Business?
Author of three Opencart book. The recent Opencart 4 book is at https://amzn.to/4dOlbOR

LEAVE A REPLY

Please enter your comment!
Please enter your name here