PHP To Go transition notes (3)

  golang, php

clipboard.png

Preface

As a PHP programmer, I feel honored. However, in the changing times, one must have sufficient knowledge to survive.

Let’s start with Go linguistics.

I hope you can have a basic understanding of Go after reading this article. This series of articles describes the way I learned Go language. The comparison between PHP code and Go code is used to distinguish and understand.

Go does not have the concept of class. This chapter compares the differences between PHP and Go in grammar usage.

Declaration class

PHP

class User{}

Go

type User struct{}

Member variable

PHP

class User{
 public $name;
 public $age;
 }

Go

type User struct {
 username string
 age      int
 }

Variable modification

PHP

class User{
 public $name;
 private $age;
 }

Go

//No wrong, there is no protected in Go, the initial letter of the variable name is public in uppercase and private in lowercase.
 type User struct {
 Username string
 Age      int
 }

Member method

PHP

class User{
 public $name;
 public $age;
 
 function setName(){
 
 }
 
 function getName(){
 
 }
 }

Go

type User struct {
 username string
 age      int
 }
 
 func (u User) setName(name string) bool {
 u.username = name
 
 return true
 }
 
 func (u User) getName() string {
 return u.username
 }

Initialization

PHP

//If PHP does not have a construction method, new objects do not need to pass parameters
 new User();

Go

//The variable declared by the internal structure of go is an optional parameter, which can be passed or not. GO has neither class concept nor construction method.
 User{"zhangsan",15}

Use

PHP

$user = new User();
 $user->getName();

Go

u := User{"zhangsan",15}
 fmt.Println(u.getName())

Thank you

Thank you for seeing here. I hope this article can help you. Thank you