PHP OOP - Traits,PHP - Static Methods,PHP - Static Properties

 PHP only supports single inheritance: a child class can inherit only from one single parent.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword:

Syntax

<?php
trait TraitName {
  // some code...
}
?>

To use a trait in a class, use the use keyword:

Syntax

<?php
class MyClass {
  use TraitName;
}
?>

Let's look at an example:

Example

<?php
trait message1 {
public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>
Try it Yourself »

Example Explained

Here, we declare one trait: message1. Then, we create a class: Welcome. The class uses the trait, and all the methods in the trait will be available in the class.

If other classes need to use the msg1() function, simply use the message1 trait in those classes. This reduces code duplication, because there is no need to redeclare the same method over and over again.


PHP - Using Multiple Traits

Let's look at another example:

Example

<?php
trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}

trait message2 {
  public function msg2() {
    echo "OOP reduces code duplication!";
  }
}

class Welcome {
  use message1;
}

class Welcome2 {
  use message1, message2;
}

$obj = new Welcome();
$obj->msg1();
echo "<br>";

$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
Try it Yourself »

Example Explained

Here, we declare two traits: message1 and message2. Then, we create two classes: Welcome and Welcome2. The first class (Welcome) uses the message1 trait, and the second class (Welcome2) uses both message1 and message2 traits (multiple traits are separated by comma).

Static methods can be called directly - without creating an instance of the class first.

Static methods are declared with the static keyword:

Syntax

<?php
class ClassName {
  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>

To access a static method use the class name, double colon (::), and the method name:

Syntax

ClassName::staticMethod();

Let's look at an example:

Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method
greeting::welcome();
?>
Try it Yourself »

Example Explained

Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).


PHP - More on Static Methods

A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):

Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    self::welcome();
  }
}

new greeting();
?>
Try it Yourself »

Static methods can also be called from methods in other classes. To do this, the static method should be public:

Example

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

class SomeOtherClass {
  public function message() {
    greeting::welcome();
  }
}
?>
Try it Yourself »

To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.

Example

<?php
class domain {
  protected static function getWebsiteName() {
    return "W3Schools.com";
  }
}

class domainW3 extends domain {
  public $websiteName;
  public function __construct() {
    $this->websiteName = parent::getWebsiteName();
  }
}

$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>
Try it Yourself »

Static properties can be called directly - without creating an instance of a class.

Static properties are declared with the static keyword:

Syntax

<?php
class ClassName {
  public static $staticProp = "W3Schools";
}
?>

To access a static property use the class name, double colon (::), and the property name:

Syntax

ClassName::$staticProp;

Let's look at an example:

Example

<?php
class pi {
  public static $value = 3.14159;
}

// Get static property
echo pi::$value;
?>
Try it Yourself »

Example Explained

Here, we declare a static property: $value. Then, we echo the value of the static property by using the class name, double colon (::), and the property name (without creating a class first).


PHP - More on Static Properties

A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::):

Example

<?php
class pi {
  public static $value=3.14159;
  public function staticValue() {
    return self::$value;
  }
}

$pi = new pi();
echo $pi->staticValue();
?>
Try it Yourself »

To call a static property from a child class, use the parent keyword inside the child class:

Example

<?php
class pi {
  public static $value=3.14159;
}

class x extends pi {
  public function xStatic() {
    return parent::$value;
  }
}

// Get value of static property directly via child class
echo x::$value;

// or get value of static property via xStatic() method
$x = new x();
echo $x->xStatic();
?>
Try it Yourself »

Namespaces are qualifiers that solve two different problems:

  1. They allow for better organization by grouping classes that work together to perform a task
  2. They allow the same name to be used for more than one class

For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.


Declaring a Namespace

Namespaces are declared at the beginning of a file using the namespace keyword:

Syntax

Declare a namespace called Html:

namespace Html;

Note: A namespace declaration must be the first thing in the PHP file. The following code would be invalid:

<?php
echo "Hello World!";
namespace Html;
...
?>

Constants, classes and functions declared in this file will belong to the Html namespace:

Example

Create a Table class in the Html namespace:

<?php
namespace Html;
class Table {
  public $title = "";
  public $numRows = 0;
  public function message() {
    echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
  }
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>


<!DOCTYPE html>
<html>
<body>

<?php
$table->message();
?>


</body>
</html>
Try it Yourself »

For further organization, it is possible to have nested namespaces:

Syntax

Declare a namespace called Html inside a namespace called Code:

namespace Code\Html;

Using Namespaces

Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it.

Example

Use classes from the Html namespace:

$table = new Html\Table()
$row = new Html\Row();
Try it Yourself »

When many classes from the same namespace are being used at the same time, it is easier to use the namespace keyword:

Example

Use classes from the Html namespace without the need for the Html\qualifier:

namespace Html;
$table = new Table();
$row = new Row();
Try it Yourself »

Namespace Alias

It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:

Example

Give a namespace an alias:

use Html as H;
$table = new H\Table();
Try it Yourself »

Example

Give a class an alias:

use Html\Table as T;
$table = new T();
Try it Yourself »

PHP - What is an Iterable?

An iterable is any value which can be looped through with a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.


PHP - Using Iterables

The iterable keyword can be used as a data type of a function argument or as the return type of a function:

Example

Use an iterable function argument:

<?php
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

$arr = ["a""b""c"];
printIterable($arr);
?>
Try it Yourself »

Example

Return an iterable:

<?php
function getIterable():iterable {
  return ["a""b""c"];
}

$myIterable = getIterable();
foreach($myIterable as $item) {
  echo $item;
}
?>
Try it Yourself »


PHP - Creating Iterables

Arrays

All arrays are iterables, so any array can be used as an argument of a function that requires an iterable.

Iterators

Any object that implements the Iterator interface can be used as an argument of a function that requires an iterable.

An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to one of the elements in the list. Each item in the list should have a key which can be used to find the item.

An iterator must have these methods:

  • current() - Returns the element that the pointer is currently pointing to. It can be any data type
  • key() Returns the key associated with the current element in the list. It can only be an integer, float, boolean or string
  • next() Moves the pointer to the next element in the list
  • rewind() Moves the pointer to the first element in the list
  • valid() If the internal pointer is not pointing to any element (for example, if next() was called at the end of the list), this should return false. It returns true in any other case

Example

Implement the Iterator interface and use it as an iterable:

<?php
// Create an Iterator
class MyIterator implements Iterator {
  private $items = [];
  private $pointer = 0;

  public function __construct($items) {
    // array_values() makes sure that the keys are numbers
    $this->items = array_values($items);
  }

  public function current() {
    return $this->items[$this->pointer];
  }

  public function key() {
    return $this->pointer;
  }

  public function next() {
    $this->pointer++;
  }

  public function rewind() {
    $this->pointer = 0;
  }

  public function valid() {
    // count() indicates how many items are in the list
    return $this->pointer < count($this->items);
  }
}

// A function that uses iterables
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a""b""c"]);
printIterable($iterator);
?>
Try it Yourself »

Post a Comment

0 Comments