[英]how to pass variable from one function to another in the same page in 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作為答案?
我的主要動機是我想學習如何在不聲明同一類的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();
-編輯:至少使用抽象的“功能”:
<?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:因為您詢問是否必須調用團隊(然后刪除該注釋):
<?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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.