PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP OOP Static

In all the previous chapters, we created objects from classes before accessing methods and properties of it.

Static Methods and Properties can be accessed without instantiating. (Without creating objects)

Static Methods

Static methods can be called directly without needing an instance of the class (an object). And, $this pseudo-variable is not available inside static methods.

Static methods and properties can be considered as escaping from Object-Oriented Programming.

Static Methods - Declaration

The static keyword is used to declare static methods.

A visibility modifier may be added before the static keyword. If there's no visibility declaration, the visibility will be public. The same rules we learned in the visibility chapter are applied for each visibility.


class MyClass {
	public static function myStaticMethod() {
		echo "Hyvor!";
	}
}

Static Methods - Accessing

  • Static methods can be accessed from outside the class using the class name and Scope Resolution Operator (::). (Only if the visibility is public)

    
    MyClass::myStaticMethod();
    
    

    Example:

    PHP Static Methods Example

    
    <?php
    class Hyvor {
    	public static function getDevSiteDomain() {
    		return 'Hyvor Developer';
    	}
    }
    echo Hyvor::getDevSiteDomain();
    
    
    Run Example ››
  • Static methods can be called from methods of other classes in the same way. To do this visibility of the static method should be public.
    
    class OtherClass {
    	public function myMethod() {
    		# visibility of myStaticMethod should be is public
    		MyClass::myStaticMethod();
    	}
    }
    
    
  • But, to access a static method from child classes of the class where the static method is declared, visibility of the static method can be protected.
    
    class OtherClass extends MyClass {
    	public function myMethod() {
    		# visibility of myStaticMethod should be is public or protected
    		MyClass::myStaticMethod();
    		# or
    		parent::myStaticMethod();
    	}
    }
    
    

    The parent keyword inside a child class refers to its parent class.

    Example:

    PHP Static Methods with Inheritance Example

    
    <?php
    class Hyvor {
    	protected static function getCompanyName() {
    		return 'Hyvor, Inc.';
    	}
    }
    class HyvorAuth extends Hyvor{
    	public $companyName;
    	public function __construct() {
    		$this -> companyName = parent::getCompanyName();
    	}	
    }
    $hyvorAuth = new HyvorAuth;
    echo $hyvorAuth -> companyName;
    
    // ERROR will be thrown
    // echo Hyvor::getCompanyName();
    
    
    Run Example ››
    Note that we can call static methods from non-static methods (In the above example, we call Hyvor::getCompanyName() from HyvorAuth class's constructor method).
    And, as Hyvor::getCompanyName() is a protected method, you can only be accessed by its child classes.
  • Static methods can be accessed from the methods in the same class using the self keyword and ::.

    
    class MyClass {
    	public static function myStaticMethod() {
    		echo "Hyvor!";
    	}
    	public function myMethod() {
    		self::myStaticMethod();
    	}
    }
    
    

Static Methods - Example

PHP Static Methods Example


<?php
class MyClass {
	public static function callMe() {
		echo "Hyvor!";
	}
	public function __construct() {
		self::callMe();
	}
}
MyClass::callMe();
echo "<br>";
new MyClass();

Run Example ››

As you see in the above example, a class can have both static and non-static methods.

Static Properties

Static properties are properties that can be used without instantiating (or creating objects from classes).

Static Properties - Declaring


class MyClass {
	public static $myStaticProperty = 'Hyvor';	
}

Static Properties - Accessing

Accessing static properties are done in the same way as static methods. The same visibility rules apply.

Static Properties - Example

PHP Static Properties Example


<?php
class MyClass {
	public static $name = 'Hyvor';
	public function __construct() {
		echo 'We are ' . self::$name;
	}
}
echo MyClass::$name . '<br>';
MyClass::$name = 'Hyvor Developer';
new MyClass();

Run Example ››

Here's the explanation.

  • In the class, we declare a static property named $name and the constructor function.
  • Then, we echo the $name from outside the class. (Line break added for a handy output)
  • Then, we change the value of the $name static property. Changing the value of a static property is done in the same way as normal variables.
  • Finally, we create a new instance from MyClass. So, the constructor function will be called. We access the static $name from the constructor using the self keyword and ::
self:: is available when you call a non-static method. But, $this is not available when you call a static method.

Why Static Methods and Properties?

Static methods and properties are widely used in PHP, especially to provide additional support for classes. Most of the time static methods are used to declare Helper and Utility functions. So, why not use normal functions for that? Truly, Object-Oriented concept gives you more ability to organize and recall your functions. One of the strongest features in OOP is autoloading, which we will learn later. Therefore, having your helper or utility functions inside a class lets you easily access them.

Here's an example usage of static methods in a class.

Usage of Static Methods in a Class


<?php
class User {
	public $firstname;
	public $lastname;

	/**
	* @param string $firstname - Firstname of the user
	* @param string $lastname  - Lastname of the user
	*/
	public function __construct($firstname, $lastname) {
		$this -> firstname = self::filterName($firstname);
		$this -> lastname = self::filterName($lastname);
	}

	/**
	* @param string $name - name to filter
	* @return string - filtered name
	*/
	static function filterName($name) {	
		// remove surrounding whitespaces
		$name = trim($name);
		// remove non-latin and non-number characters
		$name = preg_replace('/[^a-zA-Z0-9]/', '', $name);

		return $name;
	}
}
$user = new User('Michael ', '$Jackson');
echo $user -> firstname . ' ' . $user -> lastname;

Run Example ››

Here's a little explanation

  • We have a class named User to handle user's data.
  • Both first name and last name should be filtered in the same way. As the filtering method, filterName() does not need to access $this, we can simply make it a static method.
  • Next thing, take a look at the comments! Those are very descriptive and well-organized. Those types of comments are called PHP DocBlocks. Most of PHP developers tend to use this standard to write better comments. It is just a standard, not a rule, but this standard gives you more benefits. You can learn more about DocBlocks here.

Now you understand that a class can be fully static (all the methods are static). Or, you can add some static methods to a class to extend the functionalities of it as the above example.

Facebook Twitter