How to make a function where every time a variable is called is increased by 1?

Asked

Viewed 326 times

3

For example,

amid my code I do

echo $num;  //me retorna 1, mas se eu ecoar novamente a variável "$num" 
            //me retornará 2   e assim sucessivamente.

I tried a lot of different ways, but I couldn’t:

function add_um(){  
}

add_um(); //Nesse caso toda vez que eu chamasse a função ela
//me traria um número diferente do anterior, sempre acrescentando 1 unidade.

I tried with while, but fell into an infinite loop 1234567...

ADDED:

It is possible to use the $num to name a session? type, $_SESSÃO[$num]; and then nominate another session hypothetically like this: $_SESSÃO[$num++]; ?

That’s what I needed. Automatically naming sessions.

I thought of using the for to create a $i that would increase(i++) each loop to name the sessions, but I’m already working within a for and then the loops would keep repeating.

  • This number is fixed or passed as argument?

  • 1

    why not use increment http://answall.com/questions/15800/qual-a-difference%C3%A7a-entre-pr%C3%A9-e-p%C3%B3s-increment-in-javascript/15801#15801 in the answer is with javascript, but with php the logic is the same.

  • Fixed. It would be the function itself.

  • I know it’s with increment. I think I know... I just couldn’t build it. I’ll look at the link.

  • SESSION-REF: As chaves na $ _SESSION matriz associativa estão sujeitos às mesmas limitações que os nomes de variáveis ​​regulares do PHP, ou seja, eles não podem começar com um número e deve começar com uma letra ou sublinhado. What use do you want?

  • A simple $_SESSION[] would solve your problem? Creating an associative array starting with 0? http://sandbox.onlinephpfunctions.com/code/db6ab48e7989a0f8e4919ee5d30ab5b607da4ac7

  • @gmsantos added details to the question.

  • I don’t know what that has to do with the original question but, if I understood correctly, just do $_SESSION[] = array() and store all the data you need in that array, and so the superglobal will behave in the most basic way it can be, that is, an array, incrementally and automatically increasing its indices.

  • It has to do with why I needed that knowledge to do it. But as through the answers I could not give continuity alone I’m putting more points.

  • Sorry guy, I don’t mean to be rude, but you need to study a little more variables, arrays etc... go there in php manual and devour it a little, do tests with the manual examples out of your script, to understand how things work before trying to apply on something more complex. And what is that: $i<$10 ?

  • @Jader this was just a typo, I’ve corrected it. Well, you can tell the truth, man, I don’t resent it. I accept and agree and I try. I’ve been studying since morning. Before posting here I look in blogs, I watch video-lessons I read the manual, but the manual is very technical for those who are learning, it’s not like reading a history book that says so-and-so did it in such a year and ready you memorized/learned. When I talk here in the forum my mind opens. I am not only looking for ready codes and I am aware that no one has obligation to post them to me.

  • @Jader But while I’m chasing, and I’ve already learned a lot for those who study "alone", I simply ask to see if I don’t get help. But yes I will study this and the other thousands of things I lack and always be you, I do not like falsehood. Thank you for everything you have posted.

  • 2

    Please try not to ask a chameleon question (which changes from one thing to another). If you have new questions, ask new questions. I voted to close as "It is not clear what you are asking", because the question was quite confused...

  • Completely changed the initial meaning of the question... the "echo ++" no longer fits... The issue has been resolved?

  • From the point of view of the initial question it is solved. Should I remove what is not in the context of the initial question? I thought I could just sort things out.

  • I confess that I lost myself with so much editing, so I asked... and also did not understand what functionality of what you are doing. I say this because there may be a simpler way to do it.

  • 2

    @Iwannaknow, yes you can unroll things but through new questions, put a link to this one if it helps understand the new. The model of a Q&A site is completely different from that of a forum, check out the [tour] to learn more.

  • Sure Brasófilo! I will pay more attention!

Show 13 more comments

3 answers

11

Another possibility would be using magical methods.

example

$counter = new Counter();
echo $counter;
echo $counter;
echo $counter;

echo $counter, $counter, $counter;


output

123


class

class Counter
{
    public static $counter = 0;

    public function __toString()
    {
        static::$counter++;
        return (string) static::$counter;
    }
}

Whenever you give echo in a variable containing the object, the ++ incrementer of the method will be executed __toString.

PHP

The __toString() method allows a class to decide how to behave when converted to a string. For example, what echo $obj; will print. This method needs to return a string, but an E_RECOVERABLE_ERROR error is generated.

  • 2

    Although short, this is one of the best written PHP codes I’ve ever seen, congratulations.

  • :) Thank you, it’s addiction to Programador-Designer (rs)

  • 4

    Tchi munitchi... Rolled up into a little male lag with that code.

  • 2

    So I went to research and saw that magic method is really a technical term of PHP jargon. That made my day, +1.

  • Thanks @Bruno Augusto :)

  • 1

    @Renan, plus magic method

  • 2

    LOL Too Much for male lag from @Brunoaugusto (((: PHP++ for the magic presented by Papa Charlie

  • Emotion-code (LOL ++)

  • 1

    I think I was in a good mood today. That’s so. rare. .

  • Thank you! I added a question in the question.

Show 5 more comments

6


To do this in a variable:

$num = 0;
echo $num++ ;
echo $num++ ;
echo $num++ ;
echo $num++ ;

Using passage by reference:

function add_um( &$num ){  
   $num++;
}

$num = 0;
add_um( $num );
echo $num;
add_um( $num );
echo $num;
add_um( $num );
echo $num;

or even

function add_um( &$num ){  
   $num++;
   echo $num;
}

$num = 0;
add_um( $num );
add_um( $num );
add_um( $num );

Using global (do not recommend):

function add_um(){  
   global $num;
   $num++;
}

$num = 0;
add_um();

The global was a generic example, there are a thousand ways to do this.

  • 2

    If I understand the question correctly, it is better not to complicate and use direct $num++ as in your first example.

  • 1

    @bfavaretto agree. I put some possibilities to have a starting point only, but really missing details in the question.

  • Thanks! I added a question to the question.

2

There are two simple ways to do this, and with slightly different results, see which one fits your need best:

$num = 1;

echo $num++ . '<br>'; // retorna o valor atual da variável (que é 1) e soma + 1 (fica 2)

echo $num++ . '<br>'; // retorna o valor atual da variável (agora é 2) e soma + 1 (fica 3)

echo $num++ . '<br>'; // retorna o valor atual da variável (agora é 3) e soma + 1 (fica 4)

// e assim sucessivamente...

// retorno:
1
2
3

// ou desta forma:
$num = 1;

echo ($num += 1) . '<br>'; // Soma + 1 e retorna o novo valor da variável (que fica 2)

echo ($num += 1) . '<br>'; // Soma + 1 e retorna o novo valor da variável (que fica 3) 

echo ($num += 1) . '<br>'; // Soma + 1 e retorna o novo valor da variável (que fica 4)

// retorno:
2
3
4

For each page request, the counter sum 1, just do so:

session_start();

if (!isset($_SESSION['num'])) $_SESSION['num'] = 0;

$num =& $_SESSION['num'];

echo $num++;

Remembering that this is per session, that is, each user will have an independent counter while their session is alive...

  • Thank you! I added a question in the question.

  • @Iwannaknow was very confused about your doubt, but I think that’s what I put in the answer...

  • But first I have to declare $num=0; right? Inside the bracket is in a no $ even?

  • @Iwannaknow edited the answer, yes array indices should be used anyway with quotes and without the $, unless the name or value of the index is the value of the variable...

  • Okay, but I don’t understand one thing. You set the session name to "num," isn’t that a word? How am I going to increase it with the $num++?

  • @Iwannaknow when using attribution operator by reference =& causes one variable to be related to another, that is, they will always have the same value, see more in the manual...

Show 2 more comments

Browser other questions tagged

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