PHP code example of rogervila / global-namespace

1. Go to this page and download the library: Download rogervila/global-namespace library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rogervila / global-namespace example snippets


class App
{
    public function run()
    {
        $result = rand(0, 1);

        if ($result == 0) {
            // do something when $result is 0
        } else {
            // do something else when $result is 1
        }
    }
}

use PHP\PHP;

class App
{
    public function run()
    {
        $result = PHP::rand(0, 1);
        //...
    }
}

use PHP\PHP;

class App
{
    private PHP $php;

    public function __construct(PHP $php)
    {
        $this->php = $php;
    }

    public function run()
    {
        $result = $this->php::rand(0, 1);
        //...
    }
}

final class AppTest extends \PHPUnit\Framework\TestCase
{
    public function test_rand_returns_one()
    {
        // Create a mock of the package class
        $php = Mockery::mock(\PHP\PHP::class);

        // Define its return value
        $php->shouldReceive('rand')
            ->once()
            ->andReturn(1);

        // Now rand() always returns 1
        $this->assertEquals(
            1,
            $php::rand()
        );

        // Create the instance with the mocked PHP implementation
        $app = new App($php);

        // Do your application assertions here
        // ...
    }
}

use PHP\PHP;

// PHP Built-in functions
PHP::http_build_query(['foo' => 'bar']); // returns 'foo=bar'
PHP::json_encode(['foo' => 'bar']); // returns '{"foo": "bar"}'
PHP::json_decode('{"foo": "bar"}'); // return ['foo' => 'bar']
// etc...


// For WordPress projects
PHP::wp_redirect('/') // redirects to home
// etc...

// Literaly, any function, built-in or not, could be listed here

use PHP\IgnoreMissing as PHP;

PHP::http_build_query(['foo' => 'bar']); // returns 'foo=bar'

PHP::foo(); // returns null instead of triggering a "Call to undefined function" error

// missing functions return null. existing functions are called

use PHP\IgnoreAlways as PHP;

PHP::http_build_query(['foo' => 'bar']); // returns null

PHP::foo(); // returns null

// all functions return null