programing

함수 간에 생성된 PHP 변수를 다른 함수로 전달합니다.

goodjava 2023. 2. 7. 19:57

함수 간에 생성된 PHP 변수를 다른 함수로 전달합니다.

Word press와 woocommerce(e-commerce 플러그인)를 사용하여 쇼핑 카트를 커스터마이즈하고 있습니다.내 직능 범위 내에서.php 다음과 같은 변수에 데이터를 저장합니다.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $newVar = $value['data']->price;
    }
}

사용할 수 있어야 합니다.$newVar다른 기능을 사용하여 페이지의 다른 영역에 결과를 반영할 수 있습니다.예를 들어 다음과 같은 기능을 가지고 있다면 어떻게 사용합니까?$newVar그 안에?

add_action( 'another_area', 'function_name' );

function function_name() {
    echo $newVar;
}

이거 어떻게 해?

변수를 글로벌하게 만들 수 있습니다.

function add_custom_price( $cart_object ) {
    global $newVar;
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $newVar = $value['data']->price;
    }
}

function function_name() {
    global $newVar;
    echo $newVar;
}

또는 만약$newVar는 이미 글로벌 범위에서 사용할 수 있습니다.

function function_name($newVar) {
    echo $newVar;
}

// Add the hook
add_action( 'another_area', 'function_name' );

// Trigger the hook with the $newVar;
do_action('another_area', $newVar);

전치 루프 내에서 함수를 호출할 수 없는 이유가 있습니까?

function add_custom_price( $cart_object ) {
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $newVar = $value['data']->price;
        function_name($newVar);
    }
}

함수에서는 return $variable을 사용해야 합니다.

function add_custom_price( $cart_object ) {
  foreach ( $cart_object->cart_contents as $key => $value ) {
    $newVar = $value['data']->price;
  }
  return $newVar;
}

function function_name($newVar) {
//do something with $newVar
}

사용법은 다음과 같습니다.

$variable = add_custom_price( $cart_object );

$xxx = function_name($variable);

갱신:

@ChunkyBaconPlz가 말한 $newVar는 어레이여야 합니다.

function add_custom_price( $cart_object ) {
  foreach ( $cart_object->cart_contents as $key => $value ) {
    $newVar[] = $value['data']->price;
  }
  return $newVar;
}

글로벌하게 정의되어 있어도 다른 함수를 호출하는 동안 작동하지 않습니다.다른 함수의 함수를 호출하면 동작하는 것처럼 보입니다.

<?php

function one() {
    global $newVar;

        $newVar = "hello";

}

function two() {
    one();
    global $newVar;

    echo $newVar;
}
 two();

?>

이것은 범위의 문제입니다.먼저 함수 외부에서 $newVar를 인스턴스화(작성)해야 합니다.그러면 다른 기능으로 볼 수 있습니다.

스코프는 다른 오브젝트를 표시할 수 있는 오브젝트를 결정합니다.함수 내에 변수를 만들면 해당 함수 내에서만 변수를 사용할 수 있습니다.함수가 종료되면 해당 변수가 제거됩니다!

수정하려면 함수를 생성하기 전에 "$newVar"를 생성하기만 하면 됩니다.

언급URL : https://stackoverflow.com/questions/18517705/pass-php-variable-created-in-one-function-to-another