0

I have the following code, where I want to instantiate the class Username by $object = new Username. The class Username extends to class Database (which is the class in the require_once() command). And I get the error Fatal error: Uncaught Error: Class 'Username' not found in..... But when I change class Username extends Database to class Username (i.e., When it doesn't extend anymore to class Database), I get the error Fatal error: Uncaught Error: Call to undefined method Username::some() in..... I don't know what's my mistake..

<?php
require_once 'database.class.php';

if(isset($_POST['some'])){
    $sql = 'SELECT * FROM noti WHERE name=:name';
    $params = [
        'name' => $_POST['some']
    ];
    $object = new Username;
    $number = $object->some($sql, $params);
    if($number>0){
        echo 'Username Exists.';
    }
    else{
        echo '';
    }
}

class Username extends Database{
    public function some($sql, $params){
        return $this->num_rows($sql, $params);
    }
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
user13491419
  • 13
  • 1
  • 5

1 Answers1

0

It's because your logic which attempts to instantiate Username is above the code which defines it. So, when you attempt to instantiate it, it is not defined - yet. Put the class definition before its instantiation.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Well then why does work when I remove `extends Database` part and give me the error _Fatal error: Uncaught Error: Call to undefined method Username::some() in..._? – user13491419 May 17 '20 at 10:07
  • @user13491419 If you want the gritty details of exactly what's going on under the hood, I'd recommend [this answer about late binding](https://stackoverflow.com/a/29630034/4680018). The short version is to always declare your classes (or interfaces, etc) before referencing them, although PHP will be able to work around this in some cases (notably where there is no inheritance). – iainn May 17 '20 at 10:20