xref: /PHP-8.4/tests/classes/__set__get_001.phpt (revision f8d79582)
1--TEST--
2ZE2 __set() and __get()
3--FILE--
4<?php
5class setter {
6    public $n;
7    public $x = array('a' => 1, 'b' => 2, 'c' => 3);
8
9    function __get($nm) {
10        echo "Getting [$nm]\n";
11
12        if (isset($this->x[$nm])) {
13            $r = $this->x[$nm];
14            echo "Returning: $r\n";
15            return $r;
16        }
17        else {
18            echo "Nothing!\n";
19        }
20    }
21
22    function __set($nm, $val) {
23        echo "Setting [$nm] to $val\n";
24
25        if (isset($this->x[$nm])) {
26            $this->x[$nm] = $val;
27            echo "OK!\n";
28        }
29        else {
30            echo "Not OK!\n";
31        }
32    }
33}
34
35$foo = new Setter();
36
37// this doesn't go through __set()... should it?
38$foo->n = 1;
39
40// the rest are fine...
41$foo->a = 100;
42$foo->a++;
43$foo->z++;
44var_dump($foo);
45
46?>
47--EXPECTF--
48Setting [a] to 100
49OK!
50Getting [a]
51Returning: 100
52Setting [a] to 101
53OK!
54Getting [z]
55Nothing!
56Setting [z] to 1
57Not OK!
58object(setter)#%d (2) {
59  ["n"]=>
60  int(1)
61  ["x"]=>
62  array(3) {
63    ["a"]=>
64    int(101)
65    ["b"]=>
66    int(2)
67    ["c"]=>
68    int(3)
69  }
70}
71