Execute code when instantiating PHP class?
I want the code to run whenever I create a new object. For example, see this:
<?php
class Test {
echo 'Hello, World!';
}
$test = new Test;
?>
I want it to echo "Hello, World!" whenever i create a new instance of this object without calling the function after that. Is it possible?
+1
a source to share
3 answers
You should read the constructor
<?php
class MyClass {
public function __construct() {
echo "This code is executed when class in instanciated.";
}
}
?>
+8
a source to share