构造一个类并从php中的命令行运行方法

时间:2016-08-18 00:38:54

标签: php command-line-interface

我正在尝试构建一个类并从该实例表单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'];
        }

1 个答案:

答案 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;
    }
...