in php.net the following is written: Classes should be defined before instantiation (and in some cases this is a requirement). can anyone give an example when it is required? because a typical use of it doesn't require, like in this example that works ok:
<?php
$class = "a" ;
$ob = new $class() ;
class a
{
var $city = "new york" ;
}
echo $ob->city ;
?>
This won't work:
new Foo;
if (true) {
class Foo { }
}
Conditionally declared classes must come first. Basically, anything that's at the "top level" of the file is handled directly by the parser while parsing the file, which is the step before the runtime environment executes the code (including new Foo). However, if a class declaration is nested inside a statement like if, this needs to be evaluated by the runtime environment. Even if that statement is guaranteed to be true, the parser cannot evaluate if (true), so the actual declaration of the class is deferred until runtime. And at runtime, if you try to run new Foo before class Foo { }, it will fail.
If you call magic method __toString inside your class it generates fatal error : Class "MicroTimer" not found:
<?php
$pageTimer = new MicroTimer();
class MicroTimer {
private $startTime, $stopTime;
function __construct()
{
$this->startTime = microtime(true);
}
public function stop()
{
$this->stopTime = microtime(true);
}
public function elapsed()
{
if ($this->stopTime)
return round($this->stopTime - $this->startTime, 4);
return round(microtime(true) - $this->startTime, 4);
}
public function __toString()
{
return (string) $this->elapsed();
}
}
//$pageTimer = new MicroTimer();
?>
If instantiation follows after class definition, it works fine. Tested with php8.2. Problem arose in pi os bullseye showing phpLiteAdmin v1.9.8.2 with Google Chrome browser. Can also be seen with command line: php -f phpliteadmin.php.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With