×
Clear all filters including search bar
Valeri Tandilashvili's PHP Notes
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->addError('email', 'email must be a valid email');
}
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}
class OtherSubClass extends BaseClass {
// inherits BaseClass's constructor
}
// In BaseClass constructor
$obj = new BaseClass();
// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();
// In BaseClass constructor
$obj = new OtherSubClass();
class myClass {
final function myFunction() {
echo "Parent";
}
}
// ERROR because a final method cannot be overridden in child classes.
class myClass2 extends myClass {
function myFunction() {
echo "Child";
}
}
The above code will generate the following error:Fatal error: Cannot override final method myClass::myFunction() in /home/user/scripts/code.php on line 9
self
keyword is needed to access a static property from a static method in a class definitionclass myClass {
static $myProperty = 42;
static function myMethod() {
echo self::$myProperty;
}
}
myClass::myMethod();
class myClass {
static $myStaticProperty = 42;
}
echo myClass::$myStaticProperty;
final class A {
final public static function who() {
echo __CLASS__;
}
}
class B extends A {
}
B::who();
Fatal error: Class B may not inherit from final class (A)
$this
inside static methodsclass Greeting {
public $nonStatic = 'some value';
public static function hello() {
return $this->nonStatic;
}
}
// echo Greeting::hello();
$obj1 = new Greeting();
echo $obj1->hello();
After executing the above code, following error will be generated:Fatal error: Uncaught Error: Using $this when not in object context
$this
inside static methodsclass Circle {
public static $pi = 3.1415926535;
public $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pow($this->radius, 2) * self::$pi;
}
public function getPerimeter() {
return $this->radius * 2 * self::$pi;
}
}
$circle1 = new Circle(5);
echo "\nArea: " . $circle1->getArea();
echo "\nPerimeter: " . $circle1->getPerimeter();
function foo()
{
static $numOfCalls = 0;
$numOfCalls++;
echo "this function has been executed " . $numOfCalls . " times" . PHP_EOL;
}
foo();
foo();
foo();
After executing the ebove code, $numOfCalls
static variable gets incremented and the following text is printed:this function has been executed 1 times
this function has been executed 2 times
this function has been executed 3 times
constant can not be changed
static variable can not be accessed with the class object
dollar sign is needed to access static variable inside and outside of the class
constant name can not be a keyword, e.g. class (BUT: function, self, parent, static)
Similarities :
both of them are class members
both of them are accessible with "self" keyword inside the class