, Ne olup bittiğini anlamak için bu kodu düşünün lütfen:
<?php // bar.php
$one = 1;
$two = 2;
ve
<?php // foo.php
$someVar = 'var';
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
}
foo();
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
gibi bir çıktısı şey
Array
(
[0] => someOtherVar
[1] => one
[2] => two
)
Array
(
[0] => GLOBALS
[1] => _ENV
[2] => HTTP_ENV_VARS
[3] => argv
[4] => argc
[5] => _POST
[6] => HTTP_POST_VARS
[7] => _GET
[8] => HTTP_GET_VARS
[9] => _COOKIE
[10] => HTTP_COOKIE_VARS
[11] => _SERVER
[12] => HTTP_SERVER_VARS
[13] => _FILES
[14] => HTTP_POST_FILES
[15] => _REQUEST
[16] => someVar
)
As you can see, inside the function scope of foo(), you have access to the vars included in bar.php, but once the function is executed ve control flow gets back to the global scope, e.g. after the call to foo() the vars are unavailable, because they have not been exported outside the function scope. If you had included bar.php outside the function scope, e.g.
include 'bar.php'; // instead of foo()
print_r(array_keys(get_defined_vars()));
olsun istiyorum
Array
(
...
[16] => someVar
[17] => one
[18] => two
)
Placing a lot of variables into global scope bears the danger of polluting the global scope ve risking variable name clashing. That is, one include file might have a $row variable ve another might have one too ve they overwrite each other. It is better to capsule stuff that belongs together into Classes/Objects ve/or substitute the global scope with a Registry pattern.
Ben çok OOP yaklaşımı tercih ederken, yine olsa yerde fonksiyonu ile yapabiliriz. Sadece işlev çağrısı gerekli değişken döndürür.
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// this is why I do not like this approach $one pops out all of a sudden.
// I can deduct, it has to be in bar.php, but if you do that often, your
// code will be very hard to read.
return $one;
}
$user = foo(); // will contain $one then
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
// gives
Array
(
...
[16] => someVar
[17] => user
)
Of course, if you'd want to have all the variables declared during the call to foo(), you would have to place them into an array, since only one value can be returned at a time. But this is basically when you notice it gets clumsy ve switching to classes feels natural (well, at least to me).