Menu
CoddyTech

Constructors and validation

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

Ruby Class#new calls initialize and returns the new object. PHP new invokes __construct, with optional promoted typed properties. Ruby initialize has no direct property-promotion syntax; declaring PHP types still does not replace domain validation.

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

Ruby program

class Tag
  attr_reader :text
  def initialize(text)
    @text = text
  end
end
puts Tag.new("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 Ruby Developers

Practice on your own: Online PHP compiler