Answer the question
In order to leave comments, you need to log in
How to solve the problem of returned objects?
You need to display the name of the payment client. Let's take this example:
class Payment
{
/**
* @var Customer|null
*/
protected $customer;
public function getCustomer()
{
return $this->customer;
}
public function setCustomer(Customer $customer)
{
$this->customer = $customer;
}
}
class Customer
{
public function getFirstname()
{
return 'Name';
}
}
/** @var Payment $payment */
echo $payment->getCustomer()->getFirstname();
public function printCustomerFirstname(Payment $payment)
{
if ($payment->getCustomer()) {
echo $payment->getCustomer()->getFirstname();
}
}
/** @var Payment $payment */
printCustomerFirstname($payment);
Answer the question
In order to leave comments, you need to log in
1.
class Payment
{
//...
public function getCustomerFirstname()
{
return $this->customer ? $this->customer->firstname : null;
}
}
echo ($c = $payment->getCustomer()) ? $c->getFirstname() : '[удален]';
Не стоит применять слишком много "магии" или заглушек, а то в итоге станет проблематично понять где именно данных нет, а где просто пустое значение.
Errors cannot be suppressed. Put try catch if it's not a critical error and catch the exception. Or check that it's not zero.
ObjectHelper::getValue($payment,'customer.firstname',$defaultValue);
1.
As you might guess, it happens that there is no client in the payment. Removed, for example.
public function printCustomerFirstname(Payment $payment)
{
if ($payment->getCustomer()) {
echo $payment->getCustomer()->getFirstname();
}
}
public function getCustomerFirstname(): string
{
if(!$this->getCustomer()){
throw new \Exceptions\CustomerNotFound;
}
return $this->getCustomer()->getFirstname();
}
try{
$customerName = $payment->getCustomerFirstname();
}
catch( \Exceptions\CustomerNotFound $ex){
$customerName = null;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question