7

For example I have the following code:

function a($param) { function b() { echo $param; } b(); } a("Hello World!"); 

That throws an E_NOTICE error because $param is of course undefined (in b()).

I cannot pass $param to b() because b() should be a callback function of preg_replace_callback(). So I had the idea to save $param in $GLOBALS.

Is there any better solution?

6
  • FYI, b would be called a closure if it has access to $param. Commented Jul 16, 2011 at 15:08
  • @delnan: Which PHP version do you use? Commented Jul 16, 2011 at 15:10
  • @Felix Kling: None, why are you asking? Closures are a language-agnostic concept. Commented Jul 16, 2011 at 15:12
  • @delnan: Oh sorry, I actually wanted to ask the OP ;) Commented Jul 16, 2011 at 15:17
  • OP? I have PHP 5.3.1 on XAMPP. Commented Jul 16, 2011 at 15:20

4 Answers 4

12

If you are using PHP 5.3, you could use anonymous function with use keyword instead:

<?php function a($param) { $b = function() use ($param) { echo $param; }; $b(); } a("Hello World!"); 
Sign up to request clarification or add additional context in comments.

1 Comment

I'd never seen this functionality before. +1 for teaching me something new here.
1

BTW, since this was tagged functional-programming: in most functional programming languages, you would just refer to param, and it would be in scope, no problem. It's called lexical scoping, or sometimes block scoping.

It's typically languages without explicit variable declarations (eg "assign to define") that make it complicated and/or broken. And Java, which makes you mark such variables final.

Comments

0

I'd suggest using objects here.

Class a { private $param; private static $instance; public function __construct($param){ $this->param = $param; self::$instance = $this; } public function getParam(){ return $this->param; } public static function getInstance(){ return self::$instance; } } function b(){ echo a::getParam(); } 

Comments

0

I suggest the use of each function lonely, and call the second function from the first function passing parameters.

It do your code more clear because each function do a single set of operations.

<?php function a($param) { b($param); } function b($param) { echo $param; } a("Hello World!"); ?> 

5 Comments

But I want to use b() as a callback function of preg_replace_callback. So with your solution I have to make $param globally available.
Maybe you must consider other alternatives since the solution above by Ondrej Slinták only works in PHP 5.3. In PHP 5.2 it returns parse error in line 4.
Yes, but the script I build only minimizes my own scripts (so 5.3.1). But how would look an alternative with preg_replace_callback? Can you give me an example?
Before PHP 5.3 create_function() was used. php.net/manual/en/function.create-function.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.