Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 147 ยท Functions

Closure Binding and Scope

Learn how PHP closures are bound to $this and a class scope - Closure::bind, bindTo, call, fromCallable, static closures, callable strings and common pitfalls.

Every PHP closure carries two hidden pieces of context besides the variables it captured with use: a bound object (what $this means inside the closure) and a class scope (which class's private and protected members it may touch). When you create a closure inside a method, both are taken from that method automatically. When you create it outside any class, it has neither.

PHP lets you change both after the fact. With Closure::bind(), bindTo() and call() you can take a plain function and run it "as if" it were written inside another class. That sounds strange, but it is the machinery behind template engines, test helpers, dependency-injection containers and DSLs. This lesson shows how it works, what the pitfalls are, and when a static closure is the better choice.

You should already know the basics from Anonymous Functions and Closures and the rules about visibility from Classes and Objects.

Where $this comes from

A closure defined inside a method automatically binds $this to the object the method was called on, and its scope to the class:

PHP Automatic binding inside a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The closure is used outside the class, yet it can modify the private $count, because its scope is Counter. The output is 1, 2, 3 on separate lines.

Arrow functions (fn) behave the same way: they bind $this automatically when created in a method.

Binding with Closure::bind and bindTo

Closure::bind($closure, $newThis, $newScope) returns a new closure (the original is untouched) with a different $this and scope. The instance method $closure->bindTo($newThis, $newScope) does the same thing.

The classic use is reading a private property from the outside:

PHP Reading a private property with bindTo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call fails with Error: Using $this when not in object context. After binding, both versions print Mia has 250.75.

The third argument decides what the closure may see:

Call $this Scope (visible private/protected members)
bindTo($obj) $obj Kept from the original closure
bindTo($obj, Foo::class) $obj Members of Foo
bindTo($obj, $obj) $obj Members of $obj's class
bindTo(null, Foo::class) none Static members of Foo
bindTo($obj, 'static') $obj Keep the current scope (the default string)

Passing only the object is a common mistake: the closure gets a $this but still cannot touch private members, because its scope did not change. You almost always want the scope argument too.

flowchart LR
    A["Plain closure<br/>no $this, no scope"] -->|"bindTo($account, Account::class)"| B["New closure<br/>$this = $account<br/>scope = Account"]
    A -. "unchanged" .-> A

bindTo never modifies the original closure; it returns a second closure with the new context.

call(): bind and run in one step

When you only need a one-off execution, Closure::call($newThis, ...$args) temporarily binds the closure to an object, uses that object's class as the scope, calls the closure, and returns the result:

PHP Closure::call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because call() rebinds for just that call, the shorter code is a good fit for tests and debugging helpers. It cannot take a separate scope; the scope is always the class of the object you pass.

Adding behavior to existing objects

Binding lets a class stay small while behavior is attached from outside. Here is a tiny "macro" system: methods registered at runtime and executed with $this pointing to the object.

PHP Runtime macros with bound closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The macros read the private $items thanks to the scope argument. Laravel's Macroable trait works on exactly this idea. See Magic Methods for __call.

Static closures

If a closure does not need $this, you can declare it static. A static closure cannot be bound to an object; PHP emits a warning and returns null if you try:

PHP Static closures refuse an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Static closures matter for two reasons:

  • Memory. A normal closure created in a method holds a reference to $this. If you store it in a long-lived place (an event dispatcher, a cache), the object can never be garbage collected. A static closure avoids that.
  • Intent. It tells readers the function depends only on its arguments and use variables.

A good habit: in a method, make a callback static fn or static function unless it really needs $this. You can still rebind the scope of a static closure with bindTo(null, SomeClass::class), which gives it access to static members of that class.

Callable strings, arrays and fromCallable

Not every callable is a Closure object. PHP also accepts:

  • a function name as a string: 'strtoupper'
  • a static method as a string: 'Math::double'
  • an array [$object, 'method'] or [ClassName::class, 'staticMethod']
  • an invokable object (a class with __invoke)

Closure::fromCallable($callable) converts any of these into a real closure. The closure keeps the visibility context of where you called fromCallable, so you can export a private method as a closure from inside the class:

PHP fromCallable and first-class callable syntax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The exported closures work from anywhere, because they already captured the right context. The last line prints private is not callable from outside, since is_callable is evaluated in global scope. Prefer the $obj->method(...) and Class::method(...) syntax from PHP 8.1 in new code; it is shorter and the engine can optimize it.

Common pitfalls

Binding gives code access to private data. Use it for frameworks, tests and tools, not as a shortcut around a class's public API in everyday application code. If you find yourself peeking into private properties, the class probably needs a method.

  • Forgetting the scope. bindTo($obj) alone does not unlock private members.
  • Binding an arrow function that uses $this. It works, but arrow functions capture variables by value at creation; rebinding changes $this only.
  • Static closures. bindTo() with an object on a static closure fails (a warning plus null). Check the return value.
  • Rebinding closures from fromCallable on internal functions. Closures created from built-in functions cannot be rebound to a different scope.
  • Reference cycles. An object that stores a closure bound to itself forms a cycle. PHP's garbage collector can clean it, but static closures avoid the cycle in the first place.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $closure->bindTo($obj) return?

    bindTo duplicates the closure with a new $this and scope. The original keeps its old binding.
  2. 2. You want a bound closure to read a private property of Account. Which call does it?

    The second argument sets the class scope, which is what grants access to private and protected members. Passing only the object leaves the scope unchanged.
  3. 3. Why prefer static function for a callback stored in a long-lived registry?

    A non-static closure created in a method holds its object alive. A static closure captures no $this.
  4. 4. What does Closure::call($obj, ...$args) do?

    call() is a temporary bind plus invocation in one step, with the scope set to the object's class.

Summary

  • A closure has a bound object ($this) and a class scope; closures created in methods get both automatically.
  • Closure::bind() and bindTo() return a new closure with a different $this and scope. Pass the scope as the second argument to reach private members.
  • call() binds, runs and returns in one step, using the object's class as scope.
  • static closures cannot be bound to an object and do not keep $this alive.
  • Closure::fromCallable() and the f(...) syntax turn callable strings, arrays and methods into real closures that keep the correct visibility.
  • Use binding for frameworks, macros and tests, not to bypass APIs.

Next up: String Functions.