最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Accessing an instanciated class

programmeradmin1浏览0评论

I've a PHP class doing stuff:

<?php


class Cart {

    //....
}

$cart = new Cart();
$cart->init();

function deposit_total(){
    global  $cart;
    $totals = array_sum( $cart::$deposits );
    return $totals;
}

How is possible to use the $cart just instanciated in a function (deposit_total()) outside the class ?

Thank you

I've a PHP class doing stuff:

<?php


class Cart {

    //....
}

$cart = new Cart();
$cart->init();

function deposit_total(){
    global  $cart;
    $totals = array_sum( $cart::$deposits );
    return $totals;
}

How is possible to use the $cart just instanciated in a function (deposit_total()) outside the class ?

Thank you

Share Improve this question asked Feb 26, 2022 at 12:24 Sébastien SerreSébastien Serre 4843 silver badges9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I've done something like that:

<?php


class Cart {
    protected static $_instance = null;

    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    //....
}

$cart = new Cart();
$cart->init();

function EVA_Cart() {
    return Cart::instance();
}

function deposit_total(){
    $cart = EVA_Cart();
    $totals = array_sum( $cart->deposits );
    return wc_price( $totals );
}

Is it the best way ?

发布评论

评论列表(0)

  1. 暂无评论