PHP code example of dbx12 / base-object

1. Go to this page and download the library: Download dbx12/base-object 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/ */

    

dbx12 / base-object example snippets


class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;
}

// this will fail with an UnknownPropertyException because setting $privateVariable is not allowed
$instance = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;
    
    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }
}

// this will succeed
$instance = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// and this will produce an error as the setter is not visible from the global scope
$myObject->setPrivateVariable('bar');

class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;

    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }
}

$myObject = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// this will throw an UnknownPropertyException
echo $myObject->protectedVariable;

/**
 * @property-read $protectedVariable
 */
class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;

    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }

    public function getProtectedVariable()
    {
        return $this->protectedVariable;
    }
}

$myObject = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// this will succeed
echo $myObject->getProtectedVariable();

// this will succeed and your IDE will show you a hint for it thanks to the @property-read annotation
echo $myObject->protectedVariable;