I'n just learning PHP by myself, and I have a question, hope you will be able to help.
In fist style
<?php
class Fist_style
{
function method_1()
{
global $a;
return $a + 1;
}
function method_2()
{
global $a;
return $a - 1;
}
function method_3()
{
$call_1 = $this->method_1();
$call_2 = $this->method_2();
}
// In this case, how many times $a was called?
}
In second style
<?php
class Second_style
{
function method_1($a)
{
return $a + 1;
}
function method_2($a)
{
return $a - 1;
}
function method_3()
{
global $a;
//I will call both method_1 and method_2
$call_1 = $this->method_1($a);
$call_2 = $this->method_2($a);
//............
}
// In this case, how many times $a was called
}
?>
The questions are inside my code, and what style will better when develop?
Using globals is very often a recipe for disaster - as many people with experience will be happy to tell you.
The normal way of having state in a class is declaring a class property:
<?
class MyClass
{
public $a;
function __construct($valueForA) {
$this->a = $valueForA;
}
function increment()
{
$this->a += 1;
}
function decrement()
{
$this->a -= 1;
}
function plusminus()
{
$this->increment();
$this->decrement();
}
}
Which can be used like so:
$anInstance = new MyClass(10); // sets a to 10 by calling the __construct method
$anInstance->increment();
echo($anInstance->a); // 11
$anInstance->decrement();
echo($anInstance->a); // 10
Read more about oop in PHP here.
As for the question in your code, the $a
is not a method, so it can't be called.
Also, return $a -1;
does not change the global $a
(not sure if this was the intention).
Edit:
If you have a function increment like
function increment ($var) {
$var = $var - 1;
return $var;
}
then the $var
is passed in as a value - if you passed in a 5
, php only cares about 5
, not the name. Example:
$a = 5;
$incremented = increment($a);
echo($a); // echoes 5;
echo($incremented); //echoes 6
I would suggest reading up on scoping in php.