我是php oop的新手
我有两个文件这是我的代码
1)info.php
public $bd, $db1;
class Connection {
function connect() {
$this->db = 'hello world';
$this->db1 = 'hi'
}
}
2)prd.php
require_once 'info.php'
class prdinfo {
function productId() {
echo Connection::connect()->$bd;
echo Connection::connect()->$db1;
}
$prd = new prdinfo ();
$prd->productId ();
我如何在二等班中回应我的var我已经尝试过这种方式,但是我没有得到正确的输出
谢谢
应该是这样的。
info.php
class Connection {
// these two variable should be declared within the class.
protected $db; // to be able to access these variables from a diff class
protected $db1; // either their scope should be "protected" or define a getter method.
public function __construct() {
$this->connect();
}
private function connect() {
$this->db = 'hello world';
$this->db1 = 'hi';
}
}
prd.php
require_once 'info.php';
// you are accessing the Connection class in static scope
// which is not the case here.
class prdinfo extends Connection {
public function __construct() {
// initialize the parent class
// which in turn sets the variables.
parent::__construct();
}
public function productId() {
echo $this->db;
echo $this->db1;
}
}
$prd = new prdinfo ();
$prd->productId ();
这是一个基本的演示。根据您的需要进行修改。更多内容-http: //www.php.net/manual/zh/language.oop5.php
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句