Advanced PHP Features

Estimated read time 2 min read

1. Advanced PHP Features

Namespaces and Autoloading

// NamespaceExample.php
namespace MyNamespace;

class NamespaceExample {
    public function sayHello() {
        echo "Hello from NamespaceExample!\n";
    }
}

// AutoloadingExample.php
spl_autoload_register(function ($class) {
    require_once $class . '.php';
});

use MyNamespace\NamespaceExample;

$instance = new NamespaceExample();
$instance->sayHello();

Traits

// TraitExample.php
trait GreetingTrait {
    public function greet() {
        echo "Greetings!\n";
    }
}

class TraitExample {
    use GreetingTrait;
}

$instance = new TraitExample();
$instance->greet();

Generators

// GeneratorExample.php
function simpleGenerator() {
    yield "First";
    yield "Second";
    yield "Third";
}

foreach (simpleGenerator() as $value) {
    echo $value . "\n";
}

2. Object-Oriented Design Patterns

Singleton Pattern

// SingletonExample.php
class SingletonExample {
    private static $instance;

    private function __construct() {}

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

$instance = SingletonExample::getInstance();

Factory Method and Abstract Factory Patterns

// FactoryExample.php
interface Product {
    public function getName();
}

class ConcreteProduct implements Product {
    public function getName() {
        return "Concrete Product";
    }
}

interface Factory {
    public function createProduct(): Product;
}

class ConcreteFactory implements Factory {
    public function createProduct(): Product {
        return new ConcreteProduct();
    }
}

$factory = new ConcreteFactory();
$product = $factory->createProduct();
echo $product->getName() . "\n";

Observer Pattern

// ObserverExample.php
interface Observer {
    public function update(string $message);
}

class ConcreteObserver implements Observer {
    public function update(string $message) {
        echo "Received update: $message\n";
    }
}

class Subject {
    private $observers = [];

    public function addObserver(Observer $observer) {
        $this->observers[] = $observer;
    }

    public function notifyObservers(string $message) {
        foreach ($this->observers as $observer) {
            $observer->update($message);
        }
    }
}

$observer = new ConcreteObserver();
$subject = new Subject();
$subject->addObserver($observer);
$subject->notifyObservers("Hello observers!");

These examples provide a glimpse into the discussed topics. Feel free to explore and modify them to suit your lecture’s needs.

Related Articles