Class Constant and instanceof keyword in PHP

class constant
Spread the love

Class Constant is something invariable or unchanging: such as a number that has a fixed value in a given situation or universally or that is characteristic of some substance or instrument. Constants cannot be changed once it is declared. Class constants can be useful if you need to define some constant data within a class. A constant is declared inside a class with the const keyword.

Constants are case-sensitive. So, when you define a constant remember that constant should be case-sensitive. Anyway, it is recommended that when you create a constant it should be uppercase. Let’s have an example.

<?php
class Alert
{
const SUCCESS_ALERT = "Data added successfully!";
}
class constant
class constant

Well, you can use constant outside the class using (::) scope resolution operator.

echo Alert::SUCCESS_ALERT;

Well, If you want to access class constant inside the class. You can also do it. To use a constant inside the class you have to use a self keyword like the static method. Let’s see the example

Read More : Magic Methods in PHP OOP
class Math
{
const PI = 3.1416;

public function calculateArea($radius)
{
return self::PI * $radius * $radius;
}
}

In this class, first I defined a constant that is PI. Well, then defined a method which is calculatedArea. Inside the method, I used PI constant using self keyword.

By default, constant are publicly accessible. You can access constantly anywhere.

PHP constants and inheritance

The following example illustrates how to define a constant in the parent class and override it in the child class. For example:

<?php

abstract class Model
{
protected const TABLE_NAME = '';

public static function all()
{
return 'SELECT * FROM ' . static::TABLE_NAME;
}
}

class User extends Model
{
protected const TABLE_NAME = 'users';
}

class Role extends Model
{
protected const TABLE_NAME = 'roles';
}

echo User::all(); // SELECT * FROM users;

The instanceof keyword

Well, sometimes we need to check an object that which class it is from. To do that we can use the instanceof keyword. Let’s see the example then I will explain

$m = new Math();

if ($m instanceof Math) {
echo Math::PI;
}

Well, We have a Math class that I defined before. First I create an object or instance of Math class. Then check the conditions by instanceof keyword. If the condition is full-filled then print the constant value.

Read More : Inheritance in OOP example with PHP


Spread the love

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m an Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://tutspack.com

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published.