[英]PHP : call variable from another function in class
This is my class code: 这是我的课程代码:
class myClass
{
public function myFunc()
{
$myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
and I use this: 我用这个:
$nCls = new myClass;
$nCls->result();
To show Test str
form myFunc()
but nothing shown. 要显示
Test str
形式为myFunc()
但未显示任何内容。 I think the problem is : 我认为问题是:
echo myClass::myFunc()->$myvar;
Thanks for any help. 谢谢你的帮助。
You are mixing up quite a few concepts. 您正在混淆很多概念。
First, you have to create a new object of class myClass
: 首先,您必须创建类
myClass
的新对象:
$nCls = new myClass();
Then, you can call the member function (method) on that class: 然后,您可以在该类上调用成员函数(方法):
$nCls->result();
In result()
, you just call the other method using $this
: 在
result()
,您只需使用$this
调用另一个方法:
public function result()
{
echo $this->myFunc();
}
Note though that this does nothing. 请注意,尽管这没有任何作用。 The variable
$myvar
is local and not a class attribute. 变量
$myvar
是局部变量,不是类属性。 I advise you read up on object oriented programming , and object oriented PHP in particular. 我建议您阅读有关面向对象的程序设计 ,尤其是面向对象的PHP 。
class myClass {
public $myvar;
public function myFunc() {
$this->myvar = 'Test str';
return $this;
}
public function result() {
echo $this->myFunc()->myvar;
}
}
$nCls = new myClass;
$nCls->result();
You can do this but this is not a good practice. 您可以这样做,但这不是一个好习惯。
the problem is the scope, you can't call a variable within another function, define a property for the class and set it from a function then retrieve the property with result()
: 问题是范围,您不能在另一个函数中调用变量,不能为类定义属性并从函数中进行设置,然后使用
result()
检索属性:
class myClass
{
public $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo $this->myvar;
}
}
The problem is that you declare $myvar
only in the scope of method myFunc()
. 问题是您只能在方法
myFunc()
的范围内声明$myvar
。 That means it is not visible outside that method. 这意味着在该方法之外不可见。 Declare it as a class member instead:
声明为班级成员:
class myClass
{
private $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
include "views.php";
class Controller extends views{
function index(){
$this->head();
$this->home();
}
function privacy(){
$this->head();
$this->privc();
}
function about(){
$this->head();
$this->abt();
}
function address(){
$this->head();
$this->add();
}
}
$obj=new Controller();
if(isset($_GET['fun'])){
$obj->$_GET['fun']();
}
else{
$obj->index();
}
This is views.php code
class views{
function head(){
include "views/header.php";
echo "<br>this is header";
}
function abt(){
include "views/about.php";
echo "<br>This is about us page";
}
function home(){
include "views/home.php";
echo "<br>This is Home page";
}
function privc(){
include "views/privacy.php";
echo "<br>This is privacy page";
}
function add(){
include "views/address.php";
echo "<br>This is address page";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.