PHP Classes
A class is like a blueprint, Which contains a set of various types of data & methods. Like which data should be accessible outside of class and which data should be accessible only inside of class.
Example of a simple class:
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar()
{
echo $this->var;
}
}
?>
Class properties
The variables, constants & functions of the class are called as a class’s properties. These properties are defined by visibility keywords public, private & protected.
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile-time and must not depend on run-time information in order to be evaluated.
To access these properties inside of class, use pseudo-variable {$this} to accesses these properties. This pseudo-variable is predefined in every class, there is no need to declare pseudo-variable.
Example:
$this→property;
// this object may be a variables
// this object may be a constant
// this may be a function
How to declare properties
<?php
class SimpleClass
{
// valid as of PHP 5.6.0:
public $var1 = 'hello ' . 'world';
// valid as of PHP 5.3.0:
public $var2 = <<<EOD
hello world
EOD;
// valid as of PHP 5.6.0:
public $var3 = 1+2;
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVpaar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = array(true, false);
// valid as of PHP 5.3.0:
public $var8 = <<<'EOD'
hello world
EOD;
}
?>
Class constants
PHP oops supports constants in class, there are you can declare and use constant’s value per-class.
The value must be a constant expression, not a variable, a property, or a function call. It's also possible for interfaces to have constants.
How to declare constant
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT . "\n";
$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::CONSTANT."\n"; // As of PHP 5.3.0
?>
Class constant visibility modifiers
<?php
class Foo {
// As of PHP 7.1.0
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>
Output
-
BAR constant will successfully be called.
-
BAZ constant will give a fatal error because this constant visibility is private.