I’m trying to share a value of $shippingMethod
from the getMainDetails()
function to the estimateDeliveryDate()
function in the same class to run a conditional but the second function doesn’t appear to be getting the value:
private function getMainDetails($order)
{
//This value is correctly being set from my order details in Magento
$shippingMethod = strtolower($order->getShippingDescription());
}
private function estimateDeliveryDate($orderCreatedDate)
{
if ($shippingMethod == 'saturday delivery') {
echo 'Saturday Delivery';
} else {
echo 'Standard Delivery';
}
}
Wondered if someone could help?
Thank you.
2
Answers
You need to add your variable as a property, like so:
EDIT
However, a more solid approach at this would be something along these lines:
Few of things going on in that example.
I moved
shippingMethod()
into theOrder
class as it is not theDeliveryHandler
s responsibility so it should not have to care about what’s going on in that method. The data belongs to and comes fromOrder
.I made
getDeliveryDateEstimate()
return a string instead of usingecho
. This makes your code more reusable – eg what if one day you want to pass this to a template or another variable instead of echoing it. This way you keep your options open.I’m using dependency injection to pass the
Order
class into theDeliveryHandler
, thus making the public interface ofOrder
available toDeliveryHandler
.If you happen to have a laracast subscription you could check out these courses here, they explain all this stuff in a nice digestible format:
https://laracasts.com/series/object-oriented-bootcamp-in-php
https://laracasts.com/series/solid-principles-in-php
Use properties of the class (
$this->variable
), instead of local variables ($variable
). You also have a syntax error in your code, where you compare for the value of$shippingMethod
.The method below assumes that you call
getMainDetails()
before being able to useestimateDeliveryDate()
. You should however ensure that, by having$order
being passed toestimateDeliveryDate()
, and callgetMainDetails()
from there (where youreturn
from the getter instead of set a property).Alternatively, you can
return
from each function – which is what you should do from methods that is a “getter”, i.e.getMainDetails()