PHP class - get uri segments

Published on Jul 10 2016

An MVC PHP class to get uri segments which returns a string on success or bool false if key is not found.

Example usage.

The uri $_SERVER['QUERY_STRING'] example is: /articles/php

<?php  
    $uri = uri::getInstance();    
    if ($uri->segment(1))
    {
        echo $uri->segment(1);
    }   
    unset($uri);
?>

The above example will echo out the last uri segment, 'php'.

PHP uri class (uri.class.php)

<?php
namespace yourNameSpace;
class uri
{
    /** 
    * array of uri segments 
    */
    public static $segments = [];
    
    /**
    * var object $instance
    */
    private static $instance = null;
    
    /**
    * uri instance
    * return object
    */
    public static function getInstance()
    {
        if(is_null(static::$instance))
        {
            static::$instance = new uri;
        }
        return static::$instance;
    }
    
    /**
    * private construct
    * $segments string array
    */
    private function __construct()
    {
        self::$segments = explode('/', $_SERVER['QUERY_STRING']);
    }
    
    /**
    * get uri segment
    * param string $key the uri key
    * return string on success or false if key is not found
    */
    public function segment($key)
    {
        if(array_key_exists($key, self::$segments))
        {
            return self::$segments[$key];
        }
        return false;
    }
    
    /**
    * private no clone permitted
    */
    private function __clone(){
    }
}
?>

Updated by db Aug 11 2016 , filed under PHP