jjzjj

php - 在 PHP : How to call a $variable inside one function that was defined previously inside another function?

coder 2024-04-22 原文

我刚开始使用面向对象的 PHP,但遇到以下问题:

我有一个类,其中包含一个包含特定脚本的函数。我需要在同一个类下的另一个函数中调用位于该脚本中的变量。

例如:

class helloWorld {

function sayHello() {
     echo "Hello";
     $var = "World";
}

function sayWorld() {
     echo $var;
}


}

在上面的例子中,我想调用 $var ,它是一个在前一个函数中定义的变量。但这不起作用,那么我该怎么做呢?

最佳答案

你应该在类中创建 var,而不是在函数中,因为当函数结束时变量将被取消设置(由于函数终止)...

class helloWorld {

private $var;

function sayHello() {
     echo "Hello";
     $this->var = "World";
}

function sayWorld() {
     echo $this->var;
}


}
?>

如果你将变量声明为public,它可以被所有其他类直接访问,而如果你将变量声明为private,它只能在同一个类中访问..

<?php
 Class First {
  private $a;
  public $b;

  public function create(){
    $this->a=1; //no problem
    $thia->b=2; //no problem
  }

  public function geta(){
    return $this->a;
  }
  private function getb(){
    return $this->b;
  }
 }

 Class Second{

  function test(){
    $a=new First; //create object $a that is a First Class.
    $a->create(); // call the public function create..
    echo $a->b; //ok in the class the var is public and it's accessible by everywhere
    echo $a->a; //problem in hte class the var is private
    echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
    echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
  }
}
?>

关于php - 在 PHP : How to call a $variable inside one function that was defined previously inside another function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2483675/

有关php - 在 PHP : How to call a $variable inside one function that was defined previously inside another function?的更多相关文章

随机推荐