Methods and independent state
Lesson 31 of 48 in Coddy's PHP for Python Developers course.
Python writes self as the first method parameter; PHP does not list $this in the signature. Both examples keep state on instances. A class-level mutable Python value and a PHP static property would need different sharing analysis.
Instance methods use $this to reach the current object. Method calls use ->. Each instance owns its own ordinary properties, so resetting one object should not reset another. Avoid static properties for per-instance state. A type-correct method can still be behaviorally wrong if it updates the wrong instance.
Python program
class Toggle:
def __init__(self): self.on = False
def flip(self): self.on = not self.on
def label(self): return "on" if self.on else "off"
a, b = Toggle(), Toggle()
a.flip()
print(a.label(), b.label(), sep=":")Source output:
on:offPHP program
demo.php
<?php
declare(strict_types=1);
class Toggle {private bool $on=false;public function flip():void{$this->on=!$this->on;}public function label():string{return $this->on?"on":"off";}} $a=new Toggle();$b=new Toggle();$a->flip();echo $a->label(),":",$b->label(),"\n";
PHP output:
on:offChallenge
EasyInput is a list of nonnegative integer increments. Counter begins at zero; add(int $amount):void increases its private total, value():int reads it. Each new Counter is independent.
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 Counter.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__."/Counter.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function counterReport(array $values):int{$c=new Counter();foreach($values as $v)$c->add($v);return $c->value();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new Counter();$b=new Counter();$a->add(3);$a->add(2);ensure($a->value()===5 && $b->value()===0,"instance state");
echo (string)counterReport($input),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Python Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batch3Collections
Lists are PHP arraysKeys, null and presenceArray copies and referencesFiltering and dense keysOrdering without mutationRecap: word counts6Objects and state
Classes and typed propertiesConstructors and validationMethods and independent stateRecap: bounded stockPractice on your own: Online PHP compiler