在php中从命令行构造类并运行方法
我正在尝试从该实例的CLI中运行构造类和函数,如下所示:在php中从命令行构造类并运行方法,php,command-line-interface,Php,Command Line Interface,我正在尝试从该实例的CLI中运行构造类和函数,如下所示: php -r "include 'User.php'; new User(1111); returnId(); " 通过一些测试,我发现类实例正在创建中,但returnId调用了一个未定义的函数,但它是在类中定义的 以下是我的完整代码片段: include('UserRecord.php'); class User implements UserRecord{ protected $firstName; protecte
php -r "include 'User.php'; new User(1111); returnId(); "
通过一些测试,我发现类实例正在创建中,但returnId调用了一个未定义的函数,但它是在类中定义的
以下是我的完整代码片段:
include('UserRecord.php');
class User implements UserRecord{
protected $firstName;
protected $lastName;
protected $dob;
protected $_id;
public function __construct($userNumber){
$this->connectAndGetData($userNumber);
}
function returnId(){
echo $_id;
}
function connectAndGetData($userNumber){
$serverName = "localhost";
$username = "root";
$conn = mysqli_connect($serverName, $username, "", "db");
if (mysqli_connect_errno($conn)){
die("Connection failed: " . mysqli_connect_error());
}
$stmt = $conn->prepare("SELECT _id, last, first, dob FROM user WHERE un = ?");
$stmt->bind_param("s", $userNumber);
$stmt->execute();
$result = $stmt->get_result();
if( $row = $result->fetch_assoc()){
$this->firstName = $row['first'];
$this->lastName = $row['last'];
$this->dob = $row['dob'];
$this->_id = $row['_id'];
}
方法returnId()
是User
类的一个方法,因此需要在User
类的对象中调用它,如下所示:
include 'User.php';
$user = new User(1111);
$user->returnId();
好的,这里的问题如上所述,returnId
是类User
的方法,$\u id
也是如此,您需要使用$this->\u id
访问它,就像在connectAndGetData
方法中一样
include('UserRecord.php');
class User implements UserRecord{
protected $firstName;
protected $lastName;
protected $dob;
protected $_id;
public function __construct($userNumber){
$this->connectAndGetData($userNumber);
}
function returnId(){
echo $this->_id;
}
...
这给了我
注意:未定义变量:_idin…
那么我建议你去阅读关于PHP的基础知识,因为你似乎不了解PHP中作用域的基础知识。那么,你只是推荐了一些不起作用的东西吗?不,我刚刚意识到,当你一开始似乎对OOP和范围一无所知时,试图回答你的问题是毫无意义的。先做你的研究。