php override function code example

Example: php override built in functions

a. create new file with custom namespace, for example ovr.php
b. define all function that neeed to be overrided
c. include ovr.php at the beginning of each file, add namespace to that file to use same namespace used by ovr.php

//------------this is ovr.php
<?php declare(strict_types=1);
namespace dk;
/**
 * override parse_url return empty string despite null
 * 
 * @param string $url
 * @param int $component
 * @return mixed
 */
function parse_url(string $url, int $component=-1): mixed {
	$ret=	\parse_url($url, $component);
	if (is_null($ret)) $ret= '';
	return $ret;
}


//------------this is other-file.php
<?php declare(strict_types=1);
namespace dk;

$a= parse_url('/apath', PHP_URL_HOST);
var_dump($a);

Tags:

Php Example