I’m trying to write a simple class:
class tempClass
{
private $myvar = null;
function __construct()
{
$this->myvar = 'temp';
var_dump($this->myvar);
}
public function getmyvar(){
return $this->myvar;
}
}
When I call the getmyvar() public function from a page I’m including this class on (using the syntax tempClass::getmyvar();), shouldn’t the __construct() method get called automatically before I can access the public function? It doesn’t seem to– I have to do something like:
$myclass = new tempClass();
$myclass->getmyvar();
in order to have the constructor called. Is there a way to “autoconstruct” this class when calling a class function, rather than having to do the __construct code within every function?
Thanks!
The constructor is called when the object instance is “constructed.” In other words, it happens when the instance is created.
When you execute this line:
a new object is instantiated, and the constructor is executed.
When you use
::no object is instantiated, so the constructor is not called.