First, object-oriented
Php:
class rectangle{ private $width; private $height; private $color; public function __construct ($ width, $height, $color) { $ this->width = $width; $this->height = $height; $this->color = $color; } public function setcolor ($color) { $this->color = $color; } public function getcolor () { return $this->color; } public function arEA () { return $this->width * $this->height; }} $r 1 = new rectangle (12, 2, "White"); $ R2 = new rectangle (9, 4, "Blue");echo "area of r1 is ". $ R1->area (). " \ n ";echo " area of r2 is ". $r 2->area ()." \ n ";echo " color of r2 is ". $r 2->getcolor ()." \ n ";echo " set new color\n ", $r 2->setcolor (" green ");echo " Color of r2 is ". $r 2->getcolor ()." \ n ";
Go
Package Mainimport "FMT" type Rectangle struct {width, height float64color string}//If the declaration receiver is specified, when invoked with the T type, go automatically converts to *t, too TM Smart. Func (R *rectangle) setcolor (color string) {R.color = Color}func (R Rectangle) area () float64 {return r.width * r . Height}func Main () {r1: = rectangle{12, 2, "white"}r2: = rectangle{9, 4, "Blue"}fmt. Println ("Area of R1 is:", R1.area ()) fmt. Println ("Area of R2 is:", R2.area ()) fmt. Println ("Color of R2 is:", R2.color) fmt. Println ("Set new color") R2. SetColor ("green")//equivalent to (&R2). SetColor ("green"), here R2 do not need to pass the address, of course, the address is also good, just go will automatically help convert, there is no need fmt. Println ("Color of R2 is:", R2.color)}
Same problem the go language and PHP implementation comparison