Menu
CoddyTech

Constructors and validation

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

C# constructors share the class name and can be overloaded. PHP uses __construct and supports constructor property promotion. C# records and primary constructors have additional rules that should not be inferred from the concise PHP promotion syntax.

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

C# program

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
class Tag{public string Text {get;} public Tag(string text){Text=text;}}
 static void Main() {
  Console.WriteLine(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 C# Developers

Practice on your own: Online PHP compiler