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

后端 未结 2 450
陌清茗
陌清茗 2020-12-05 21:59

I\'m just starting with Object Oriented PHP and I have the following issue:

I have a class that contains a function that contains a certain script. I need to call a

相关标签:
2条回答
  • 2020-12-05 22:24

    you should create the var in the class, not in the function, because when the function end the variable will be unset (due to function termination)...

    class helloWorld {
    
    private $var;
    
    function sayHello() {
         echo "Hello";
         $this->var = "World";
    }
    
    function sayWorld() {
         echo $this->var;
    }
    
    
    }
    ?>
    

    If you declare the Variable as public, it's accessible directly by all the others classes, whereas if you declare the variable as private, it's accessible only in the same class..

    <?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
      }
    }
    ?>
    
    0 讨论(0)
  • 2020-12-05 22:32

    Make $var a class variable:

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

    I would avoid making it a global, unless a lot of other code needs to access it; if it's just something that's to be used within the same class, then that's the perfect candidate for a class member.

    If your sayHello() method was subsequently calling sayWorld(), then an alternative would be to pass the argument to that method.

    0 讨论(0)
提交回复
热议问题