PHP code example of tarsisioxavier / magic-object

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

    

tarsisioxavier / magic-object example snippets




agicObject\DataModel;

class ExampleClass extends DataModel
{
    // Your code here...
}

$exampleObject = new ExampleClass();

var_dump($exampleObject);



agicObject\DataModel;

class ExampleClass extends DataModel
{
    // Your code here...
}

$exampleObject = new ExampleClass();

// This property doesn't exist.
$exampleObject->name = 'Dolores Abernathy';

// Will print: Dolores Abernathy.
print $exampleObject->name . "\n";

// You can also pass an array when creating the object defining the object's attributes.
$anotherExampleObject = new ExampleClass([
    'name' => 'Dolores Abernathy',
    'email' => '[email protected]'
]);

// Will print: Dolores Abernathy ([email protected])
print $anotherExampleObject->name;
print ' ';
print '(' . $anotherExampleObject->email . ")\n";



agicObject\DataModel;

class ExampleClass extends DataModel
{
    public function getDocumentAttribute()
    {
        return $this->cpf ?? $this->cnpj;
    }
}

// CPF and CNPJ are types of civilian registers in Brazil.
// These were randomly generated in the website: https://www.4devs.com.br/gerador_de_pessoas
$exampleObject = new ExampleClass([
    'name' => 'Dolores Abernathy',
    'cnpj' => '38.789.452/0001-77',
]);

// The object don't have any CPF, so it'll print the CNPJ instead.
print $exampleObject->document . "\n";



agicObject\DataModel;

class ExampleClass extends DataModel
{
    public function setDateAttribute($value)
    {
        $this->attributes['date'] = $value->format('Y-m-d H:i');
    }
}

$datetime = new \DateTime('now');

$object = new ExampleClass(['date' => $datetime]);

// Will print only the the year-month-day hour:minute.
print $object->date . "\n";

$anotherObject = new ExampleClass();
$anotherObject->date = $datetime;

// Same output.
print $object->date . "\n";



agicObject\DataModel;

trait SimpleTrait
{
    public string $helloWorld;

    public function bootSimpleTrait()
    {
        $this->helloWorld = 'ZA WARUDO!';
    }
}

class ExampleClass extends DataModel
{
    use SimpleTrait;
}

$object = new ExampleClass();

echo $object->helloWorld . "\n";

// Output:
// ZA WARUDO!