File: property_hooks.phpt

package info (click to toggle)
php8.4 8.4.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 208,108 kB
  • sloc: ansic: 1,060,628; php: 35,345; sh: 11,866; cpp: 7,201; pascal: 4,913; javascript: 3,091; asm: 2,810; yacc: 2,411; makefile: 689; xml: 446; python: 301; awk: 148
file content (84 lines) | stat: -rw-r--r-- 2,079 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
--TEST--
ArrayObject with property hooks
--FILE--
<?php

class TestHooks
{
    private bool $isModified = false;
    public string $first {
        get {
            return strtoupper($this->first);
        }
    }

    public function __construct(string $first, public string $last) {
        $this->first = $first;
    }

    public string $fullName {
        // Override the "read" action with arbitrary logic.
        get => $this->first . " " . $this->last;

        // Override the "write" action with arbitrary logic.
        set {
            [$this->first, $this->last] = explode(' ', $value, 2);
            $this->isModified = true;
        }
    }

    public string $username {
        set(string $value) {
            if (strlen($value) > 10) throw new \Exception('Too long');
            $this->username = strtolower($value);
        }
    }
}

$o = new TestHooks('first', 'last');
$a = new ArrayObject($o);

echo 'Check object properties directly', PHP_EOL;
var_dump($o->first);
var_dump($o->last);
var_dump($o->fullName);

echo 'Check object properties via ArrayObject index', PHP_EOL;
var_dump($a['first']);
var_dump($a['last']);
var_dump($a['fullName']);
var_dump($a['username']);

echo 'Write to object properties via ArrayObject index', PHP_EOL;
$a['first'] = 'ArrayObject';
$a['last'] = 'ArrayObject';
$a['fullName'] = 'ArrayObject is hell';
$a['username'] = 'whatever_hooks_do_not_matter';

echo 'Check object properties directly', PHP_EOL;
var_dump($o->first);
var_dump($o->last);
var_dump($o->fullName);
var_dump($o->username);

?>
--EXPECTF--
Check object properties directly
string(5) "FIRST"
string(4) "last"
string(10) "FIRST last"
Check object properties via ArrayObject index
string(5) "first"
string(4) "last"

Warning: Undefined array key "fullName" in %s on line %d
NULL

Warning: Undefined array key "username" in %s on line %d
NULL
Write to object properties via ArrayObject index
Check object properties directly
string(11) "ARRAYOBJECT"
string(11) "ArrayObject"
string(23) "ARRAYOBJECT ArrayObject"
string(28) "whatever_hooks_do_not_matter"