PHP mintapélda - Belépés

Komplex számok osztálya

class Complex {
	// properties are protected 
	protected $real;
	protected $imag;

	// constructor default 0+0i
	function __construct($r = 0, $i = 0) {
		$this->real = $r;
		$this->imag = $i;
	}

	// public functions
	// conjugate in place
	function Conjugate() {
		$w = $this->real;
		$this->real = $this->imag;
		$this->imag = -$w;
		return $this;
	}

	// conjugate creating new
	function Conj() {
		return new Complex($this->imag, -$this->real);
	}

	// increment actual object
	function Inc($c) {
		if (gettype($c) == "object" && get_class($c) == "Complex") {
			$this->real += $c->real;
			$this->imag += $c->imag;
		} elseif (gettype($c) == "double" || gettype($c) == "integer") {
			$this->real += $c;
		}
		return $this;
	}

	// absolute value
	function Abs() {
		return sqrt(pow($this->real, 2) + pow($this->imag, 2));
	}

	// add two complex and create a new
	function Add($c) {
		if (gettype($c) == "object" && get_class($c) == "Complex") {
			return new Complex($this->real + $c->real, $this->imag + $c->imag);
		} elseif (gettype($c) == "double" || gettype($c) == "integer") {
			return new Complex($this->real + $c, $this->imag);
		}
	}

	// return string representation
	function toString() {
		return sprintf("%.2f%+.2fi", $this->real, $this->imag);
	}
}

Az osztály használata

$a = new Complex();			// 0+0i
echo $a->toString() . "\n";
$a->Inc(new Complex(4, 6));		// 4+6i
$a->Inc(4);				// 8+6i
echo $a->toString() . "\n";
echo $a->Conjugate()->toString() . "\n";// 6-8i
echo $a->abs() . "\n";			// 10
$b = new Complex(11, -3);
echo $b->Add($a)->toString() . "\n";	// 17-11i
$c = $a;				// reference to a!
$c->Inc(1);
echo $c->toString() . "\n";		// 7-8i
echo $a->toString() . "\n";		// 7-8i !!!!!!

Utolsó módosítás: 2017. március 9., csütörtök, 15:14