What is class constant?

You can also create a class constants in php classes. These are constants designed to be used by classes, not objects.
<?php
class Math
{
const pi = 3.14159;

}
?>

Now you can refer to the constant pi in code inside the Math class as self::pi. You can use the constant with self:: rather than $this because for class constants, there’s no object involved.

<?php
class Math
{
const pi = 3.14159;
function dis_pi()
{
echo ‘pi from inside the class ‘, self::pi , “<br>”;
}
}
?>

You can access pi outside the class. using class name.
<?php
class Math
{
const pi = 3.14159;
function dis_pi()
{
echo ‘pi from inside the class ‘, self::pi , “<br>”;
}
}

Echo ‘pi from outside the class : ‘, Math::pi, “<br>”;

?>

File name : index.php

You can also display pi using objects, if you call the public method dis_pi.
<?php
class Math
{ const pi = 3.14159;
function dis_pi()
{
echo ‘pi from inside the class ‘, self::pi , “<br>”;
}
}
Echo ‘pi from outside the class : ‘, Math::pi, “<br>”;
$obj = new Math();
$obj->dis_pi( );
?>
However, you can’t access the class constant pi using object expressions like $obj::pi or $obj->pi





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here