Global variable in all functions of the class

Asked

Viewed 10,588 times

4

Usually when I want to pull a variable that is out of class, I use global $variavel, but wanted this variable to be accessible in all functions of the class, not to be needing to "pull" in all functions, how to do?

  • 2

    You want to stop using global, which is good, and take a non-global variable that should survive throughout the application easily within each function?

  • 1

    The class has a builder ?

  • Yes and yes @Zuul

  • 2

    Why do you want to get a variable out of the class? The parameters serve precisely to pass to the methods what they need.

  • 1

    The variable must be global even, must last throughout the application and be available for all classes or it is a variable that must belong to a class?

  • @Oeslei the variable is connected with db..

  • 1

    I was going to post a comment on the other question, but as you deleted, here is an extensive table of primes: http://primes.utm.edu/primes/download.php

Show 2 more comments

3 answers

7


My understanding of the question is that it is necessary to store the connection data in a variable that can be accessed from any point of the application. A global variable is a solution to this but in fact it is not good to use it.

So the solution is to encapsulate the variable that is not global in a function by maintaining its state in a static way or using an approach considered more modern, but not necessarily better, encapsulating the variable in a static class.

Note that being static is the secret because it gives a lifespan for the variable equal to the application time, that is, the variable becomes available all the time exactly as the global variable is but has the advantage of the variable not being exposed directly creating ambiguities and conflicts with other local variables. It is better to have global functions or classes. Even this may not be the ideal solution, some would criticize this solution which is pragmatic.

class Conexao {
    private static $conexao = "dados da conexao aqui - classe";
    public static function PegaConexao() {
        return self::$conexao;
    }
}

function conexao(){
    static $conexao = "dados da conexao aqui - funcao";
    return $conexao;
}

class Uso {
    public function AbreBanco1() {
        echo conexao() . "\n";
    }
    public function AbreBanco2() {
        echo Conexao::PegaConexao();
    }
}

Uso::AbreBanco1(); //chama só para demonstrar
Uso::AbreBanco2(); //chama só para demonstrar

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

As the question does not give details I can only show a generic solution but it is easy to adapt for use according to the specific need.

It doesn’t have to have both forms, I put the two to exemplify, obviously only one AbreBanco() would actually exist. And the contents of the variable will probably be another.

  • His example is extensive and complex. Unlike mine, which is a more direct response and without the use of static private variables and/or static methods.

  • Use static methods only for functions where there is no need to change the internal state of an object. Usually static methods are auxiliary methods, written to give generic support to other methods. An example is a vector ordering method: it takes an array as a parameter and sorts it, then returns. It can be used in several places, but does not alter the internal state of any object. Therefore, he is a great candidate to become a static method.

  • 1

    Extensive and complex? Are you sure? I find it the shortest and simplest. Note that I’ve shown him two different ways to choose from. But do what he asked, his answer does not. His does not make the content available for all functions of all classes. In your content dies when the variable $a comes out of scope. People only voted for yours because they did not understand the problem. After reading your second I can only say "Amen". This is what is read in good practice manuals that do not help solve any problem. So I abhor them. They dictate rules and do not solve problems.

  • But anyway note that I do not change internal state at any time, in either case. You do this, but the problem didn’t ask you to do this.

  • No use "embellishing" the answer when the goal is another: "...queria que essa variável fosse acessível em todas as funções **da classe**". You went further. Your answer consumes more codes.

  • Read the comments, there he clarifies and gives more details of how he wants. You may complain that the question originally was not giving all the details but he chose my answer as the correct one because it solves his real problem. It is the same case that had happened there in the other question, Jorgeb gave an answer that seemed right but was not and there appeared Bacco and gave the right answer because he understood better the problem even the question not helping much.

  • He didn’t answer his last question. Therefore, the variable must belong to the same class and accessible to all functions of the same, as the question.

  • http://answall.com/questions/53794/vari%C3%a1vel-global-em-todas-as-fun%C3%A7%C3%b5es-da-classe/53797? noredirect=1#comment110288_53794 the two "yes" are for the previous comments, after I realized, so he did not answer more, was already answered.

Show 3 more comments

4

Create accessible variable for all functions of a class:

<?php

    class teste {

        /* construct */
        function __construct($variavel) {

            $this->global_variavel  = $variavel;

        }

        function checando_funcao() {

                echo $this->global_variavel;

        }

        function checando_funcao2() {

                echo $this->global_variavel;

        }

?>
  • To run a test:

        //Criando uma nova instância
    
        $variavel = 'Meu texto!';
        $a = new teste($variavel);
    
        //Executando as duas funções com os mesmos valores de uma única variável "global"
        $a->checando();  
        $a->checando_funcao2();
    

Obs:

To ensure reverse compatibility, if PHP 5 cannot find a __Construct() for a given class, it will search for the old-fashioned constructor function, which has the same class name. Effectively, it means that the only case that can generate compatibility problems would be if the class has a method called __Construct() that is used for another purpose than not initializing the object.

  • Your answer is strictly wrong. But the question was initially not very clear. It is the same problem that you complained in this comment: http://answall.com/questions/53689/montar-os-par%C3%a2metros-de-um-url-dynamically/53692#comment110408_53692 Even for coherence I am not preaching the negative in your answer but it is wrong for what the author wants. You only had those positive ones because people didn’t quite understand what the question wanted either. So you can understand that she wasn’t well formulated. What are you going to do now that you know she’s wrong?

  • Show me the sources, the rules and prove me wrong about the scope.

  • Yours is like mine? It’s not, yours does something different than what was asked. Mine was accepted at the time, yours was available for hours and the author did not consider it right. Only author can prove which one is right and he did this when he accepted. There could only be two right ones if they both produced the same result, even in different ways. Yours produces a different result than expected, yours loses its state when it leaves the scope, it doesn’t want this.

  • I think the author must have been impressed with an answer made by a reputation of 44k+ and said, "Wow! That’s what I needed. A reliable source."Talvez!

  • Since you’ve begun to belittle the author’s intelligence by speculating that he doesn’t know what solves his problem, which might even be the case if he hadn’t already demonstrated that he can get along with proper information and doesn’t need to be tutored, I realize you won’t change your mind after I show you the facts, I can’t say any more. If mine were wrong I would recognize, repair or erase, as I have done before.

1

To make a class variable member set the access modifier and then its name

public - is accessible by all class methods and outside it too.

protected - accessible only within the class and its derivatives.

private - accessible only detros of class methods.

class Teste{
   public $variavel = 'esse valor pode ser modificado externamente';

   public function foo(){
     echo $this->variavel;
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.