OOPs Tutorials
- What is OOPs
- Access Modifier
- Constructor
- Destructor
- Polymorphism
- Inheritence
- Method Overriding
- Abstract class
- Interface
- Traits
- This keyword
- static keyword
- Final keyword
- Class Constant
- Exception Handling
- Binding in php
- tostring in php
- Object Iteration
- Reflection
- Magic methods
- Namespaces
- CRUD Function
- OOPs CRUD
- CRUD Example
Important Links
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