<?php
class
ComplexNumber {
private
$real
;
private
$imaginary
;
public
function
__construct(
$real
,
$imaginary
) {
$this
->real =
$real
;
$this
->imaginary =
$imaginary
;
}
public
function
add(ComplexNumber
$complexNumber
) {
return
new
ComplexNumber(
$this
->real +
$complexNumber
->getReal(),
$this
->imaginary +
$complexNumber
->getImaginary()
);
}
public
function
subtract(ComplexNumber
$complexNumber
) {
return
new
ComplexNumber(
$this
->real -
$complexNumber
->getReal(),
$this
->imaginary -
$complexNumber
->getImaginary()
);
}
public
function
multiply(ComplexNumber
$complexNumber
) {
$real
=
$this
->real *
$complexNumber
->getReal()
-
$this
->imaginary *
$complexNumber
->getImaginary();
$imaginary
=
$this
->real *
$complexNumber
->getImaginary()
+
$this
->imaginary *
$complexNumber
->getReal();
return
new
ComplexNumber(
$real
,
$imaginary
);
}
public
function
__toString() {
return
"({$this->real}, {$this->imaginary}i)"
;
}
public
function
getReal() {
return
$this
->real;
}
public
function
getImaginary() {
return
$this
->imaginary;
}
}
$complex1
=
new
ComplexNumber(2, 3);
$complex2
=
new
ComplexNumber(1, -2);
$sum
=
$complex1
->add(
$complex2
);
$difference
=
$complex1
->subtract(
$complex2
);
$product
=
$complex1
->multiply(
$complex2
);
echo
"Sum: $sum, Difference: $difference, Product: $product"
;
?>