PHP code example of clouding / has-attributes

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

    

clouding / has-attributes example snippets


class Post
{
    use \Clouding\HasAttributes\HasAttributes;
}

$post = new Post([
    'title' => 'Hello',
    'body' => 'World',
]);

echo $post->title; // Hello
echo $post->body;  // World



interface Eatable {}

class Pig implements Eatable { }

class Zoo
{
    use \Clouding\HasAttributes\HasAttributes;

    protected $define = [
        'name' => 'string',
        'number' => 'int',
        'animal' => Eatable::class,
    ];
}

$zoo = new Zoo([
    'name' => 'Mike',
    'number' => 100,
    'animal' => new Pig(),
]);

echo $zoo->name;              // Mike
echo $zoo->number;            // 100
echo get_class($zoo->animal); // Pig

new Zoo(['name' => 999]);

// InvalidArgumentException: [name => 999] value is not equal to define type [string] 

new Zoo(['foo' => 'bar']);

// InvalidArgumentException: Key [foo] is not defined 

class Person
{
    use \Clouding\HasAttributes\HasAttributes;
}

$person = new Person([
    'id' => 100,
]);

$person->setAttributes([
    'name' => 'Marry',
    'phone' => '0912345678'
]);

$person->setAttribute('sex', 'female');

$person->age = 18;

echo $person->id;    // 100
echo $person->name;  // Marry
echo $person->phone; // 0912345678
echo $person->sex;   // female
echo $person->age;   // 18

class Person
{
    use \Clouding\HasAttributes\HasAttributes;
}

$person = new Person([
    'id' => 100,
    'name' => 'Jack',
]);

echo $person->getAttribute('id');                 // 100

echo $person->getAttribute('salary', 0);          // 0 (if key not exists return default value)

var_dump($person->getAttributes('id', 'name'));   // ['id' => 100, 'name' => 'Jack']

var_dump($person->getAttributes(['id', 'name'])); // ['id' => 100, 'name' => 'Jack']