如何在 php 中将变量从一个函数提取到同一类中的另一个函数中


How to extract variable from one function into another in same class in php

我想将变量值从一个函数使用到同一类的另一个函数中。我正在使用abstract class,我正在使用它间接地将变量声明为global。我不能将变量声明为类中的global。我的演示代码如下:

<?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();
?>

我是否可以在那里回显 105 作为答案?

的主要动机是我想学习如何使用将变量值从一个函数获取到另一个函数,而无需在同一类中声明全局请让我知道这可能吗或我需要删除我的问题?

<?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();

-- 编辑:至少使用一些抽象的"功能":

<?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:既然你问过是否必须调用 team(然后删除了该评论):

<?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();

所以,是的,它必须在某个地方调用。但是,根据您要实现的目标,有许多方法可以做到这一点。

类的每个属性都可以由同一类的每个方法访问。因此,您可以创建使用相同属性的方法。而且你不需要创建父抽象类。

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();