Go for PHP Developers: Getting Started
For all you beginner, intermediate or expert PHP developers, here’s an article which should provide you with a little guidance on how to get started writing your applications in Golang and how it compares to a similar workflow with PHP.
But first, let’s grab the things we need to start writing Go applications. Head on over to Go’s website to get it installed here. Follow the guidance there to get things setup for your OS of choice.
In this article we’ll take a look at the example test code they suggest you try to ensure your installation is working as expected.
Inside your $GOPATH
in a folder src/hello
you should have created a file called hello.go
which should contain the following:
package main
import "fmt"
func main() {
fmt.Printf("hello, world")
}
If you’ve not guessed it already, this is Go’s “Hello World”. Straight away you can spot some differences between PHP and Go, syntactically and the use of different keywords and a function called main
Now if you’re familiar with any other compiled languages (oh yeah, I forgot to mention Go is a compiled language) then you will recognise the use of the main
function, if not, basically this is the entrypoint to the application. This is what is called when you run your application, everything must come from this single point.
In PHP with a file called hello.php
we’d be looking at something like this:
<?phpecho "hello, world";
Despite the PHP implementation being way simpler, our Go application is doing way more to get things running. Go programs are built around the use of packages to include code, this is similar to PHP namespaces. And in order to print something out we need to pull in the fmt
package. This provides the library to do so.
We can emulate a similar set of code if we were to be using a namespace for our project and a “namespaced” class to handle the output for us. For example:
<?phpnamespace Main;use \Example\Fmt;function main()
{
Fmt::printf("hello, world");
}main();
Say the above package we’re pulling in provides an interface to do the same thing, the code doesn’t look at all that different. Except we’re calling the main
function ourselves.
And if we were to run the two applications we would get the same output. (In the case of the PHP application we’ll return to the first example as to not have to write the Fmt
class or provide an autoloader)
php hello.php
Outputs “hello, world”
go run hello.go
Outputs “hello, world”
Now that you’re setup you should follow the tour provided on the Go website, and take a look through “gobyexample”
https://tour.golang.org/welcome/1
In later articles we’ll look into comparing a PHP web application with a Go one.