Menu
CoddyTech

Constructors and validation

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

Java constructors share the class name and can be overloaded. PHP uses one __construct method and supports property promotion with visibility/type declarations on its parameters. Domain validation remains separate from field initialization in both languages.

__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.

Java program

import java.util.*;

class Main {
static class Tag{final String text;Tag(String text){this.text=text;}}
  public static void main(String[] args) throws Exception {
    System.out.println(new Tag("draft").text);
  }
}

Source output:

draft

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 Java Developers

Practice on your own: Online PHP compiler