如何从一个类函数调用变量到另一个类函数 [英] how to call a variable from one class function to another class function
本文介绍了如何从一个类函数调用变量到另一个类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 php oop 的新手
i am new to php oop
我有两个文件这是我的代码
I have an two files Here is my code
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 我已经尝试过这种方式,但我没有得到正确的输出
how i can echo my var in 2nd class i have tried in that way but i am not getting proper output
谢谢
推荐答案
应该是这样的.
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/en/language.oop5.php
This is a basic demonstration. Modify it as per your needs. More here - http://www.php.net/manual/en/language.oop5.php
这篇关于如何从一个类函数调用变量到另一个类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文