1

当 TestPage.php 在浏览器中运行时,'trying to create new obj...' 被回显,但没有别的。构造函数没有被调用吗?

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

测试页面.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...';
    }

    ...
}
?>
4

2 回答 2

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';
于 2012-04-12T00:37:46.943 回答
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...';
    }
}
于 2012-04-12T00:38:24.380 回答