PHP 클로저 함수의 의미

墨辰丷
풀어 주다: 2023-03-29 18:50:01
원래의
2386명이 탐색했습니다.

이 글에서는 주로 PHP 클로저 함수를 자세히 소개합니다. 클로저 함수에는 함수 이름이 없습니다. function()에 직접 변수를 전달하면 정의된 변수가 함수로 처리됩니다. 클로저 함수? 관심 있는 친구는 클로저 함수라고도 불리는

익명 함수를 참고하세요. (클로저는 콜백 함수 매개변수의 값으로 가장 많이 사용되는 함수를 지정하지 않고도 함수를 생성할 수 있습니다.

echo preg_replace_callback('~-([a-z])~', function ($match) {
  return strtoupper($match[1]);
}, 'hello-world');`
로그인 후 복사

Use use

$message = 'hello';
$example = function() use ($message){
  var_dump($message);
};
echo $example();
//输出hello
$message = 'world';
//输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
echo $example();
//重置为hello
$message = 'hello';
//此处传引用
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
//输出hello
$message = 'world';
echo $example();
//此处输出world
//闭包函数也用于正常的传值
$message = 'hello';
$example = function ($data) use ($message){
  return "{$data},{$message}";
};

echo $example('world');
로그인 후 복사

example

class Cart{
  //在类里面定义常量用 const 关键字,而不是通常的 define() 函数。
  const PRICE_BUTTER = 1.00;
  const PRICE_MILK  = 3.00;
  const PRICE_EGGS  = 6.95;

  protected $products = [];
  public function add($product,$quantity){
    $this->products[$product] = $quantity;
  }
  public function getQuantity($product){
    //是否定义了
    return isset($this->products[$product])?$this->products[$product]:FALSE;
  }
  public function getTotal($tax){
    $total = 0.0;
    $callback = function($quantity,$product) use ($tax , &$total){
      //constant 返回常量的值
      //__class__返回类名
      $price = constant(__CLASS__."::PRICE_".strtoupper($product));

      $total += ($price * $quantity)*($tax+1.0);
    };
    //array_walk() 函数对数组中的每个元素应用用户自定义函数。在函数中,数组的键名和键值是参数
    array_walk($this->products,$callback);
    //回调匿名函数
    return round($total,2);

  }
}


$my_cart = new Cart();
$my_cart->add('butter',1);
$my_cart->add('milk',3);
$my_cart->add('eggs',6);


print($my_cart->getTotal(0.05));
로그인 후 복사

Summary: 이 기사의 전체 내용이 도움이 되기를 바랍니다. 모두가 배워요

관련 추천:

php Metaphone() 함수 및 php localeconv() 함수 예제 자세한 설명

php 이미지 업로드 클래스 및 호출 방법

php array_unshift( ) 배열 키 수정에 대한 참고 사항 및 예제 분석

위 내용은 PHP 클로저 함수의 의미의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!