nameless nameless - 9 days ago 5
PHP Question

PHP Class Variable

I know there are some threads about it already but nothing seems to work... I'm trying to make something like a global class variable in PHP, so in theory I want something like that:

(PseudoCode follows):

class GlobalVarClass{

globalVar $price;

function doSomethingWithThePrice(){

//get some Values, etc..
$this->price = $xyz;

}

function needThePriceNow(){
//this is where the price is needed now, so something like
echo $this->price;
}

}


How can I do this? Btw.: I can NOT set this value in constructor, as there I have it not available yet....

I'm using Laravel btw., if this makes something easier...

Edit:
To be exact, this is the code I have:

class VoucherController extends Controller
{
private $_apiContext;

protected $voucherValue;

public function __construct()
{
$this->_apiContext = PayPal::ApiContext(
config('services.paypal.client_id'),
config('services.paypal.secret'));

$this->_apiContext->setConfig(array(
'mode' => 'sandbox',
'service.EndPoint' => 'https://api.sandbox.paypal.com',
'http.ConnectionTimeOut' => 30,
'log.LogEnabled' => true,
'log.FileName' => storage_path('logs/paypal.log'),
'log.LogLevel' => 'FINE'
));

}

public function index(){
return view('voucher.createVoucher');
}

public function payVoucher(Request $request){
$userInfo = \App\User::where('id','=',\Auth::user()->id)
->first();

if($userInfo->street == ""){
$request->session()->flash('alert-info', 'Vor der ersten Bestellung müssen Sie erst Ihre Daten vervollständigen');
return redirect('/editData');
}

$itemList = PayPal::itemList();

$payPalItem = PayPal::item();
$payPalItem->setName('Gutschein')->setDescription('Gutschein für Shopping Portal')->setCurrency('EUR')->setQuantity(1)->setPrice($request->input('voucherValue'));

$total = $request->input('voucherValue');

$this->voucherValue = $total;

$itemList->addItem($payPalItem);

$payer = PayPal::Payer();
$payer->setPaymentMethod('paypal');

$details = PayPal::details();
$details->setShipping("0")
->setSubtotal($total);

$amount = PayPal:: Amount();
$amount->setCurrency('EUR');
$amount->setTotal(($total));
$amount->setDetails($details);

$transaction = PayPal::Transaction();
$transaction->setAmount($amount);
$transaction->setItemList($itemList);
$transaction->setDescription('Ihr Gutschein');

$redirectUrls = PayPal:: RedirectUrls();
$redirectUrls->setReturnUrl(action('VoucherController@getDone'));
$redirectUrls->setCancelUrl(action('VoucherController@getCancel'));

$payment = PayPal::Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setRedirectUrls($redirectUrls);
$payment->setTransactions(array($transaction));

$response = $payment->create($this->_apiContext);

$redirectUrl = $response->links[1]->href;

return Redirect::to($redirectUrl);
}


public function getDone(Request $request)
{
$id = $request->get('paymentId');
$token = $request->get('token');
$payer_id = $request->get('PayerID');

$payment = PayPal::getById($id, $this->_apiContext);

$paymentExecution = PayPal::PaymentExecution();

$paymentExecution->setPayerId($payer_id);
$executePayment = $payment->execute($paymentExecution, $this->_apiContext);

// Clear the shopping cart, write to database, send notifications, etc.

// Thank the user for the purchase

//Gutscheincode generieren, in DB eintragen, und per Mail verschicken

$voucherCode = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 12);
$voucher = new Voucher;
$voucher->voucherValue = $this->voucherValue;
$voucher->voucherCode = $voucherCode;
$voucher->save();

return view('voucher.buyDone', ['voucherCode' => $voucherCode, 'payment' => $payment]);
}


So I'm doing a PayPal payment. In the function
payVoucher
, I get the voucherValue (which is the variable that should be accessible in the other function) from the
request
, then in the function
getDone
I need to access it to enter it into the DB. How can I do this?

Answer

Based on your comment, the second method is called after a redirect. That is a new request and as all variables you set in your script cease to exist when the script finishes, your original object with the properties you set will no longer exist.

There are several ways to pass the value to the new request, like a query variable in the url, a session variable or for example database storage.

Using a session or some other kind of server-side storage keeps the value on the server so that is what I would recommend:

public function payVoucher(Request $request){
    ...
    $_SESSION['PayPal']['voucherValue'] = $total;
    ...
}


public function getDone(Request $request)
{
    ...
    $voucher->voucherValue = $_SESSION['PayPal']['voucherValue'];
    // You need to delete it?
    unset($_SESSION['PayPal']['voucherValue']);
    ...
}

Note that I am assuming that a session has been started at the top of the script.

Comments