Home > Backend Development > PHP Tutorial > PHP 传值问题?

PHP 传值问题?

WBOY
Release: 2016-06-06 20:28:56
Original
1053 people have browsed it

<code>function str_emoji($str,$cdn){
  function empic($h){
    $p=dechex(str_replace(array('',';'),'',$h));
    return '<img src="'.%24cdn.%24p.'.png" alt="'.$h.'" class="smiley">';
    //$cdn无法传进来!!!
  };
  $str=preg_replace('#(\&\#[0-9]{6}\;)#ie','empic("\\1")',$str);
  return $str;
};

echo str_emoji($str,$_POST['face']);</code>
Copy after login
Copy after login

$cdn无法传进函数??

回复内容:

<code>function str_emoji($str,$cdn){
  function empic($h){
    $p=dechex(str_replace(array('',';'),'',$h));
    return '<img src="'.%24cdn.%24p.'.png" alt="'.$h.'" class="smiley">';
    //$cdn无法传进来!!!
  };
  $str=preg_replace('#(\&\#[0-9]{6}\;)#ie','empic("\\1")',$str);
  return $str;
};

echo str_emoji($str,$_POST['face']);</code>
Copy after login
Copy after login

$cdn无法传进函数??

php中的闭包中变量的作用范围和js中的稍微有点不同。要使闭包函数外的变量作用于闭包函数内,可用use关键字。参考下面一个例子:

<code class="php">function test($a, $b) {
    $t = function ($c) use ($a, $b) {
        return $a + $b + $c;
    };
    return $t(3);
}

echo test(1, 2);  // 6</code>
Copy after login

$cdn不在empix()的作用域下,它是str_emoji()的全局变量。要把$cdn 传进empix()。

<code class="php">//自己测试下
function str_emoji($str,$cdn){
  function empic($h,$cdn){
    $p=dechex(str_replace(array('',';'),'',$h));
    return '<img src="'.%24cdn.%24p.'.png" alt="'.$h.'" class="smiley">';
    //$cdn无法传进来!!!
  };
  $str=preg_replace('#(\&\#[0-9]{6}\;)#ie','empic("\\1",'.$cdn.')',$str);
  return $str;
};</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template