-
-
Notifications
You must be signed in to change notification settings - Fork 1
Examples
Greg Bowler edited this page Jun 20, 2023
·
2 revisions
use Gt\DataObject\DataObject;
$obj = (new DataObject())
->with("name", "Cody")
->with("colour", "orange")
->with("food", [
"biscuits",
"mushrooms",
"corn on the cob",
]);
echo json_encode($obj), PHP_EOL;
Output:
{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}
use Gt\DataObject\DataObjectBuilder;
$jsonString = '{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}';
$builder = new DataObjectBuilder();
$obj = $builder->fromObject(json_decode($jsonString));
echo "Hello, ",
$obj->getString("name"),
"! Your favourite food is ",
$obj->getArray("food")[0],
PHP_EOL;
Output:
Hello, Cody! Your favourite food is biscuits
use Gt\DataObject\DataObject;
require __DIR__ . "/../vendor/autoload.php";
// Set an object with all string values, similar to a web requests:
$obj = new DataObject();
$obj = $obj->with("one", "1");
$obj = $obj->with("two", "two");
$obj = $obj->with("pi", "3.14159");
// Automatically cast to int:
$int1 = $obj->getInt("one");
$int2 = $obj->getInt("two");
$int3 = $obj->getInt("pi");
echo "One: $int1, two: $int2, three: $int3", PHP_EOL;
Output:
One: 1, two: 0, three: 3
Note how the decimal data is lost in the cast to int, but how the original data is not lost.
use Gt\DataObject\DataObject;
$obj = new DataObject();
$obj = $obj->with("arrayOfData", [
1,
2,
3.14159
]);
echo "The first element in the array is: ",
$obj->getArray("arrayOfData", "int")[0], // note the type check of "int"
PHP_EOL;
Output:
The first element in the array is: PHP Fatal error: Uncaught TypeError: Array index 2 must be of type int, double given
PHP.Gt/DataObject is a separately maintained component of PHP.Gt/WebEngine.