I am trying to figure out how to pass variables across files in wordpress
and came across this little code here in form-checkout.php woocommerce.
do_action( 'woocommerce_before_checkout_form', $checkout );
// If checkout registration is disabled and not logged in, the user cannot checkout.
if ( ! $checkout->is_registration_enabled() && $checkout->is_registration_required() && ! is_user_logged_in() ) {
echo esc_html( apply_filters( 'woocommerce_checkout_must_be_logged_in_message', __( 'You must be logged in to checkout.', 'woocommerce' ) ) );
return;
}
The variable $checkout is not defined in the file, seems to come from different file but I cannot find any include which tracks the variable to its origin.
Just wondering how to pass variables across files without include or require,
Not sure if this is wordpress specific or PHP related, but if anybody could help, I would really appreciate it.
Thanks in advance !!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It’s set by the code that includes the template, and is in-scope when the file is included – from the include documentation:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
form-checkout isn’t used in isolation, it’s included from another class with wc_get_template:
wc_get_template( 'checkout/form-checkout.php', array( 'checkout' => $checkout ) );
and that argument becomes $checkout: wc_get_template calls extract on that array before it does the actual include to generate $checkout in-scope.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0