Menu
CoddyTech

Constructors and validation

Lesson 30 of 48 in Coddy's PHP for Go Developers course.

Go has no automatic constructor syntax, so a New-style function can return a value and validation error. PHP __construct initializes objects and may throw. PHP property promotion stores arguments but does not enforce business invariants on its own.

__construct initializes an object after new allocates it. Constructor property promotion can both declare and initialize a property using a visibility modifier on the parameter. Validate invariants rather than merely storing invalid input. If a subclass declares a constructor, call parent::__construct explicitly when parent initialization is needed.

Go program

package main
import ("fmt")
type Score struct{Points int}
func NewScore(points int)(Score,error){if points<0{return Score{},fmt.Errorf("negative")};return Score{Points:points},nil}

func main(){
score,err:=NewScore(3);if err!=nil{panic(err)};fmt.Println(score.Points)
}

Source output:

3

PHP program

demo.php

<?php
declare(strict_types=1);
class Tag {public function __construct(public string $text){}} $t=new Tag("draft"); echo $t->text,"\n";

PHP output:

draft
challenge icon

Challenge

Easy

Input is an integer. Capacity constructor accepts nonnegative limit, rejecting negatives with InvalidArgumentException. limit():int returns it. Driver prints invalid for rejected construction.

The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.

Edit Capacity.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.

Try it yourself

<?php
declare(strict_types=1);
require_once __DIR__."/Capacity.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function capacityReport(int $n):string{try{return (string)(new Capacity($n))->limit();}catch(InvalidArgumentException $e){return "invalid";}}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Capacity(3))->limit()===3,"constructor value");try{new Capacity(-2);throw new RuntimeException("accepted negative");}catch(InvalidArgumentException $e){}
echo capacityReport($input),"\n";
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PHP for Go Developers

Practice on your own: Online PHP compiler