PHP code example of stefna / php-code-builder

1. Go to this page and download the library: Download stefna/php-code-builder 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/ */

    

stefna / php-code-builder example snippets


$file = new PhpFile();
$file->setSource("spl_autoload_register('$autoloaderName');");

new PhpParam('string', 'test') => string $test
new PhpParam('object', 'test', null) => object $test = null

$param = new PhpParam('DateTimeInterface', 'date');
$param->allowNull(true);
$param->getSource() => ?DateTimeInterface $date

$param = new PhpParam('float', 'price', 1.5);
$param->allowNull(true);
$param->getSource() => ?float $price = 1.5

$func = new PhpFunction(
    'testFunc',
    [
        'param1', // Simple parameter
        new PhpParam('int', 'param2', 1),
    ],
    "return $param1 + $param2",
    null, // no docblock
    'int'
);

echo $func->getSource();


function testFunc($param1, int $param2 = 1): int
{
    return $param1 + $param2;
}

$method = new PhpMethod('private', 'test', [], 'return 1', null, 'int');
echo $method->getSource();

-------

private function test(): int
{
    return 1;
}

$method = new PhpMethod(
    'private',
    'test',
    [],
    'return 1',
    new PhpDocComment('Test Description')
);
echo $method->getSource();

-------
/**
 * Test Description
 */
private function test()
{
    return 1;
}

$method = new PhpMethod('protected', 'test', [], 'return 1');
$method->setStatic();
echo $method->getSource();

-------

protected static function test()
{
    return 1;
}

$method = new PhpMethod('public', 'test', [], 'return 1');
$method->setFinal();
echo $method->getSource();

-------

final public function test()
{
    return 1;
}

$method = new PhpMethod('public', 'test', [], 'return 1', null, 'int');
$method->setAbstract();
echo $method->getSource();

-------

abstract public function test(): int;