php构造函数没有被调用?或者其他的东西?

时间:2012-04-12 00:35:59

标签: php

当在浏览器中运行TestPage.php时,'尝试创建新的obj ...'是echo'd,但没有别的。构造函数没有被调用吗?

这不是任何一个班级的完整代码,但希望有人告诉我哪里出错了......

TestPage.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/plain; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        class MyClass {
        $api_key = 'somestring';
        $username = 'username';
        echo 'trying to create new obj...';
        $myObj = new MyClass($api_key, $username);
        echo 'new obj created...';

    ...
        ?>
    </body>
</html>

MyClass.class.php

<?php
class MyClass {
    protected $_api_key;
    protected $_username;


    public function __construct($api_key, $username) {
        echo 'entered constructor...';
        $this->_api_key = $api_key;
        $this->_username = $username;
        echo 'leaving constructor...';
    }

    ...
}
?>

2 个答案:

答案 0 :(得分:4)

您需要将其实际定义为一个类。那看起来像是:

class MyClass {
    protected $_api_key;
    protected $_username;


    public function __construct($api_key, $username) {
        echo 'entered constructor...';
        $this->_api_key = $api_key;
        $this->_username = $username;
        echo 'leaving constructor...';
    }
}

只需将您拥有的代码放在一个文件中并命名就不会自行执行任何操作。

此外,如果您尚未包含该文件,则需要包含该文件。类似的东西:

include 'MyClass.class.php';

答案 1 :(得分:1)

您需要class个关键字来定义一个类http://php.net/manual/en/language.oop5.basic.php以获取一些基本示例

尝试

class MyClass
{
 protected $_api_key;
    protected $_username;


    public function __construct($api_key, $username) {
        echo 'entered constructor...';
        $this->_api_key = $api_key;
        $this->_username = $username;
        echo 'leaving constructor...';
    }
}