undefinedfix
Sign in

How to introduce external values into class?

silvesthu edited in Tue, 09 Aug 2022

Question 1: does class receive external values?

class connection {
   var $host = 'XXXX';
   var $username = 'aaab';
   var $password = 'aaa';

   $do = new mysqli($host, $username, $password, $config['db']);
}

I have changed the value of $config ['db '] according to the host on the top, so when I read database a when testing the domain and database B when I read the formal domain, but I find that I can't throw this in, and it will display an error. Like a general function, you can use global to receive external values, just add global $config; but how can I achieve this in class?

Question 2: does the function in class have to be global to receive external values? (although general functions also need to go through global, I would like to say that with the principle of object orientation, is it unnecessary?)

class get {
   public function get_information() {
      global $request;

      $render = mysqli_fetch_array($do->query(
         "SELECT * FROM `user`
         WHERE `session` = '{$request['session']}' "
      ));

      return $render;
   }
}

( $ Do doesn't care about it, because problem one is still being solved. If it can be solved, you can use inheritance) when you use get of get class_ information () Announce global in it $ request ; To receive external values $ What is the way to request without using global? Can it be inherited? Or other ways. Thank you!

3 Replies
marc
commented on Tue, 09 Aug 2022

PHP class through the construction method__ Construct to pass parameters.

for instance:

<?php

class mydb {

    protected $use_dbname;
    
    protected $dbh;
    
    public function __construct( $host, $username, $password, $dbname ) {

        $this->dbh = new mysqli( $host, $username, $password, $dbname );
        
        // 将传入的参数赋值到内部变量就可以在内部其他地方调用了
        $this->use_dbname = $dbname;
    }
    
    public function query( $query ) {
        
        // 这里可以获取 $this->use_dbname
        
        $result = $this->dbh->query( $query );
        return $result;
    }

    // more 
}

// 使用
$mydb = new mydb( 'host', 'user', 'pwd', 'dbname' );
// $mydb->query('SELECT * FROM `user` WHERE user_id = 1;')
zcnfk
commented on Tue, 09 Aug 2022

https://www.51-n.com/t-4004-1... You can take a look at this. I don't know if it can solve your problem

Jinja_dude
commented on Wed, 10 Aug 2022

Do you have any misunderstanding about class?? Let's see?

lock This question has been locked and the reply function has been disabled.