Exception: Serialization of 'Closure' is Not Allowed
When attempting to use closures within test methods, an "Exception: Serialization of 'Closure' is not allowed" error may occur.
Problem
The code fragment below uses a closure to specify a custom file path for storing emails:
<code class="php">protected function _initMailer() { ... elseif ('testing' === APPLICATION_ENV) { // ... $callback = function() { return 'ZendMail_' . microtime(true) .'.tmp'; }; // ... }</code>
Resolution
Solution 1: Replace Closure with Regular Function
Replace the closure with a regular function:
<code class="php">protected function _initMailer() { ... elseif ('testing' === APPLICATION_ENV) { // ... function emailCallback() { return 'ZendMail_' . microtime(true) . '.tmp'; } $callback = "emailCallback"; // ... }</code>
Solution 2: Use Array Variable for Indirect Method Call
Utilize an array variable to call a method indirectly:
<code class="php">protected function _initMailer() { ... elseif ('testing' === APPLICATION_ENV) { // ... $callback = array($this, "aMethodInYourClass"); // ... }</code>
This allows you to define the method within the class and pass it to the callback using an array.
The above is the detailed content of How to Resolve \'Exception: Serialization of \'Closure\' is Not Allowed\' Error Using Closures in Test Methods?. For more information, please follow other related articles on the PHP Chinese website!