PHP code example of silvanus / structs

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

    

silvanus / structs example snippets




namespace YourNameSpace\Structs;

// Parent class.
use Silvanus\Structs\AbstractStruct;

class Employee extends AbstractStruct
{    
    public string $name;    
    public string $department;
    public int $salary;
}




use YourNameSpace\Structs\Employee;

$employee = new Employee();

// Set up data by property.
$employee->name       = 'Eiríkr Blóðøx';
$employee->department = 'Norway';
$employee->salary     = 954;

echo $employee->name; // Eiríkr Blóðøx

/**
 * You can only use properties set in class / struct level.
 */
$employee->hobbies = "Raiding"; // Throws CanNotSetPropertyException.
echo $employee->hobbies // Throws CanNotGetPropertyException




use YourNameSpace\Structs\Employee;

$data = array(
	'name' => 'Eiríkr Blóðøx',
	'department' => 'Norway',
	'salary' => 954,
	// Setting incorrect fields here will likewise throw exceptions.
);

$employee = new Employee($data);




namespace YourNameSpace\Structs;

// Different parent class
use Silvanus\Structs\AbstractStructImmutable;

class EmployeeImmutable extends AbstractStructImmutable
{    
    public string $name;    
    public string $department;
    public int $salary;
}




use YourNameSpace\Structs\EmployeeImmutable;

$data = array(
	'name' => 'Eiríkr Blóðøx',
	'department' => 'Norway',
	'salary' => 954,
	// Setting incorrect fields here will likewise throw exceptions.
);

$employee = new EmployeeImmutable($data);

// You can access the properties.
echo $employee->name;
echo $employee->department;
echo $employee->salary;

// ... But you cannot edit them.
$employee->name = 'Eiríkr inn rauða'; // Throws CanNotSetPropertyException.