2009-05-17 52 views
1

我希望代码在我创建新对象时运行。例如,看到这个:创建PHP类实例时运行代码?

<?php 

class Test { 
echo 'Hello, World!'; 
} 

$test = new Test; 

?> 

我希望它回声“你好,世界!”每当我创建这个对象的一个​​新实例时,不需要以后调用函数。这可能吗?

回答

8

你应该阅读有关constructor

<?php 
class MyClass { 
    public function __construct() { 
     echo "This code is executed when class in instanciated."; 
    } 
} 
?> 
6
class Test { 
function __construct(){ 
    echo 'Hello, World!'; 
} 
} 
+1

值得一提的是:这是PHP5 +的方式..应该不重要,但仍然.. – 2009-05-17 23:47:09

+3

公平地说,PHP4现在基本上已经过时。 – Turnor 2009-05-18 00:43:06

2

或者对PHP 4的使用:

class Test { 
    function Test { 
     echo 'Hi'; 
    } 
} 

编辑:这也适用于PHP 5,所以这是做到这一点的最好办法。