开发者

PHP best method to affect variables in a function

开发者 https://www.devze.com 2023-01-23 13:04 出处:网络
I\'m playing around with hooking into functions, the hook will call the method of another object, what is the best way of changing the value $price in the parent function before it is returned?

I'm playing around with hooking into functions, the hook will call the method of another object, what is the best way of changing the value $price in the parent function before it is returned?

function _product_price ($price,$taxable = true)
{
    $shop->_hook('PRODUCT_PRICE_BEFORE');
    $price = 100.00;
    $shop->_hook('PRODUCT_PRICE_AFTER');
    return number_format($price,2);
}

Thanks guys, would this be a suitable solution?

function _product_price ($price,$taxable = true)
{
    global $shop;
    $shop->_hook('PRODUCT_PRICE_BEFORE');
    $price = 100.00;
    $shop-&g开发者_运维技巧t;passedArgs['price'] = $price;
    $shop->_hook('PRODUCT_PRICE_AFTER');
    return number_format($shop->passedArgs['price'],2);
}
function _hook ()
{
    global $shop;
    $shop->passedArgs['price'] = 23.00;
    return;
}


Since you likely want to register arbitrary methods for hooks, have a look at

  • Subject/Observer and
  • Event Dispatcher


I'd pass the variables to the point either:

  • as an array of references, (array('price' => &$price); would make any change to the $var['price'] variable in a function later on / deeper reflect in the 'in-scope' $price.
  • set the variables to the point as an object-property and just pass the current observable object as a parameter.
0

精彩评论

暂无评论...
验证码 换一张
取 消