[英]How to extract variable from one function into another in same class in php
I want to use variable value from one function into another function of same class. 我想将变量值从一个函数转换为同一类的另一个函数。 I am using
abstract class
using which I am declaring variable as global
indirectly. 我正在使用
abstract class
通过它我将变量间接声明为global
。 I can not declare variable as global
in the class. 我不能在类中将变量声明为
global
变量。 My demo code is as follows: 我的演示代码如下:
<?php
abstract class abc
{
protected $te;
}
class test extends abc
{
public function team()
{
$te = 5;
$this->te += 100;
}
public function tee()
{
$tee = 51;
return $this->te;
}
}
$obj = new test();
echo $obj->tee();
//echo test::tee();
?>
Is this possible that I can echo 105 as answer there? 是否可以在其中回显105作为答案?
My main motive is I want to learn that how to get variable value from one function into another using without declaring that global in the same class Please let me know Is this possible OR I need to delete my question ? 我的主要动机是我想学习如何在不声明同一类的global的情况下将一个函数的变量值转换为另一个函数,请告诉我这是可能的还是我需要删除我的问题?
<?php
abstract class abc
{
protected $te;
}
class test extends abc
{
public function __construct() {
$this->te = 5;
}
public function team()
{
$this->te += 100;
}
public function tee()
{
return $this->te;
}
}
$obj = new test();
$obj->team();
echo $obj->tee();
-- edit: to make at least some use of the abstract "feature": -编辑:至少使用抽象的“功能”:
<?php
abstract class abc
{
protected $te;
abstract public function team();
public function tee()
{
return $this->te;
}
}
class test extends abc
{
public function __construct() {
$this->te = 5;
}
public function team()
{
$this->te += 100;
}
}
$obj = new test();
$obj->team();
echo $obj->tee();
-- edi2: since you've asked whether you must invoke team (and then deleted that comment): -edi2:因为您询问是否必须调用团队(然后删除该注释):
<?php
abstract class abc
{
protected $te;
abstract public function team();
public function tee()
{
$this->team();
return $this->te;
}
}
class test extends abc
{
public function __construct() {
$this->te = 5;
}
public function team()
{
$this->te += 100;
}
}
$obj = new test();
echo $obj->tee();
So, yes, it has to be invoked somewhere. 因此,是的,必须在某个地方调用它。 But depending on what you're trying to achieve there are numerous ways to do so.
但是,根据您要实现的目标,可以采用多种方法。
Each property of the class can be accessed by each method of the same class. 相同类的每个方法都可以访问该类的每个属性。 So you can create methods which are working with the same property.
因此,您可以创建使用相同属性的方法。 And you don't need to create parent abstract class.
而且您不需要创建父抽象类。
class test
{
protected $te = 5;
public function team()
{
$this->te += 100;
}
public function tee()
{
return $this->te;
}
}
$obj = new test();
$obj->team();
echo $obj->tee();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.