简体   繁体   中英

Included class inside another class is not declared PHP

I have the following __construct of a selfmade class;

public function __construct($ip, $user, $pass, $product) {
    $this->_ip = $ip;
    $this->_user = $user;
    $this->_pass = $pass;
    $this->_product = $product;

    $this->ssh = new Net_SSH2($this->_ip);
    if (!$this->ssh->login($this->_user, $this->_pass)) {
        return 'Login Failed';
    }
    $this->sftp = new Net_SFTP($this->_ip);
    if (!$this->sftp->login($this->_user, $this->_pass)) {
        return 'Login Failed';
    }
}

Now the problem is that it says Net_SSH2 and Net_SFTP is not declared, but I have included those classes at the page, im not sure, but can it be that I have to pass those classes into this class instead of just calling them? If yes, how do I do that?

A better solution is to use autoload.

function __autoload($class_name) {
    require_once $class_name . '.php';
}

Now, when you ask for a new class, it will be auto loaded.

Try this.

Have you included those classes using a require , include or an autoload function?

If you haven't, make sure the files in which those classes are defined are loaded.

Now, we need to check for the namespace.

At the top of the Net_SFTP , is there a namespace [SOMETHING] ? If there is, you must refer to the fully qualified class name, or use this class.

An example:

<?php

namespace VendorName\BundleName;

class Net_SFTP { 
    ....
}

?>

Now, in order to use this class, we must do one of the following:

<?php

use VendorName\BundleName\Net_SFTP;

...
$this->ssh = new Net_SFTP(...);
...
?>

Or, directly:

<?php

...
$this->ssh = new VendorName\BundleName\Net_SFTP(...);
...

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM