where does $checkout in form-checkout.php woocommerce come from?

All we need is an easy explanation of the problem, so here it is.

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' ) ) );

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 !!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply