note 127656 added to language.oop5.properties
| From: | kchlin dot lxy at gmail dot com | Date: | Tue, 20 Sep 2022 15:39:31 +0000 |
| Subject: | note 127656 added to language.oop5.properties | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219602@lists.php.net to get a copy of this message | ||
From PHP 8.1
It's easy to create DTO object with readonly properties and promoting constructor
which easy to pack into a compact string and covert back to a object.
<?php
# Conversion functions.
# Pack object into a compack JSON string.
function cvtObjectToJson( object $poObject ): string
{
return json_encode( array_values( get_object_vars( $poObject )));
}
# Unpack object from a JSON string.
function cvtJsonToObject( string $psClass, string $psString ): object
{
return new $psClass( ...json_decode( $psString ));
}
# DTO example class.
final class exampleDto
{
final public function __construct(
public readonly int $piInt,
public readonly ?int $pnNull,
public readonly float $pfFloat,
public readonly string $psString,
public readonly array $paArray,
public readonly object $poObject,
){}
}
# Example with export only public properties of given object.
$exampleDtoO = new exampleDto( 1, null, .3, 'string 4', [], new stdClass() );
$stringJson = cvtObjectToJson( $exampleDtoO );// [1,null,0.3,"string 4",[],{}]
$objectO = cvtJsonToObject( exampleDto::class, $stringJson );
# Check and var_dump variables.
echo $exampleDtoO == $objectO
? 'Objects equal, but not identical.'. PHP_EOL
: 'Objects not equal neither identical.'. PHP_EOL
;
var_dump($exampleDtoO, $stringJson, $objectO);
# Output
/*
Objects equal, but not identical
object(exampleDto)#6 (6) {
["piInt"]=>
int(1)
["pnNull"]=>
NULL
["pfFloat"]=>
float(0.3)
["psString"]=>
string(8) "string 4"
["paArray"]=>
array(0) {
}
["poObject"]=>
object(stdClass)#7 (0) {
}
}
string(29) "[1,null,0.3,"string 4",[],{}]"
object(exampleDto)#8 (6) {
["piInt"]=>
int(1)
["pnNull"]=>
NULL
["pfFloat"]=>
float(0.3)
["psString"]=>
string(8) "string 4"
["paArray"]=>
array(0) {
}
["poObject"]=>
object(stdClass)#9 (0) {
}
}
*/
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.173 (proxied: 178.173.101.68)
----
Manual Page -- https://php.net/manual/en/language.oop5.properties.php
Edit -- https://main.php.net/note/edit/127656
Del: integrated -- https://main.php.net/note/delete/127656/integrated
Del: useless -- https://main.php.net/note/delete/127656/useless
Del: bad code -- https://main.php.net/note/delete/127656/bad+code
Del: spam -- https://main.php.net/note/delete/127656/spam
Del: non-english -- https://main.php.net/note/delete/127656/non-english
Del: in docs -- https://main.php.net/note/delete/127656/in+docs
Del: other reasons-- https://main.php.net/note/delete/127656
Reject -- https://main.php.net/note/reject/127656
Search -- https://main.php.net/manage/user-notes.php