我正在尝试构建一个类并从该实例表单CLI运行一个函数,如下所示:
php -r "include 'User.php'; new User(1111); returnId(); "
throguh throguh一些测试我已经发现正在创建类实例,但是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'];
}
答案 0 :(得分:1)
方法returnId()
是User
类的方法,因此您需要在User
类的对象中调用它,如下所示:
include 'User.php';
$user = new User(1111);
$user->returnId();
好的,您的问题如上所述,returnId
是类User
的方法,因此$_id
,您需要使用$this->_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;
}
...