ellriley
ellriley

Reputation: 655

php constructor not getting called? or something?

When TestPage.php is run in browser, 'trying to create new obj...' is echo'd, but nothing else. Is the constructor not getting called?

This isn't the full code for either class, but hopefully it's enough for someone to tell me where I'm going wrong...

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...';
    }

    ...
}
?>

Upvotes: 1

Views: 4280

Answers (2)

Baba
Baba

Reputation: 95101

You need class keyword to define a class please http://php.net/manual/en/language.oop5.basic.php for some basic examples

Try

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...';
    }
}

Upvotes: 1

clexmond
clexmond

Reputation: 1549

You need to actually define it as a class. That would look like:

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...';
    }
}

Just placing the code you have in a file and naming it won't do anything on its own.

Additionally, you'll need to include that file if you haven't already. Something like:

include 'MyClass.class.php';

Upvotes: 4

Related Questions