xref: /PHP-8.1/Zend/tests/closure_038.phpt (revision f8d79582)
1--TEST--
2Closure 038: Rebinding closures, change scope, different runtime type
3--FILE--
4<?php
5
6class A {
7    private $x;
8
9    public function __construct($v) {
10        $this->x = $v;
11    }
12
13    public function getIncrementor() {
14        return function() { return ++$this->x; };
15    }
16}
17class B extends A {
18    private $x;
19    public function __construct($v) {
20        parent::__construct($v);
21        $this->x = $v*2;
22    }
23}
24
25$a = new A(0);
26$b = new B(10);
27
28$ca = $a->getIncrementor();
29var_dump($ca());
30
31echo "Testing with scope given as object", "\n";
32
33$cb = $ca->bindTo($b, $b);
34$cb2 = Closure::bind($ca, $b, $b);
35var_dump($cb());
36var_dump($cb2());
37
38echo "Testing with scope as string", "\n";
39
40$cb = $ca->bindTo($b, 'B');
41$cb2 = Closure::bind($ca, $b, 'B');
42var_dump($cb());
43var_dump($cb2());
44
45$cb = $ca->bindTo($b, NULL);
46var_dump($cb());
47
48?>
49--EXPECTF--
50int(1)
51Testing with scope given as object
52int(21)
53int(22)
54Testing with scope as string
55int(23)
56int(24)
57
58Fatal error: Uncaught Error: Cannot access private property B::$x in %s:%d
59Stack trace:
60#0 %s(%d): Closure->{closure}()
61#1 {main}
62  thrown in %s on line %d
63