PDA

View Full Version : Global چیست؟



Mohammad Minaei
یک شنبه 08 خرداد 1384, 14:34 عصر
دوستان! این GLOBAL که می نویسن و بعدشم چند تا متغیر چه می کنه؟!
کتابشو دارما! ولی هر چی گشتم چیزی در موردش پیدا نکردم.
اگه با مثال توضیح بدید که دیگه خیلی لطف کردید!

ممنون!

oxygenws
یک شنبه 08 خرداد 1384, 15:35 عصر
RTFM (http://php.net/manual/en)

houtanal
یک شنبه 08 خرداد 1384, 17:53 عصر
The global keyword
First, an example use of global:

Example 7-1. Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
global $a, $b;

$b = $a + $b;
}

Sum();
echo $b;
?>



The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example 7-2. Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}

Sum();
echo $b;
?>



The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example 7-3. Example demonstrating superglobals and scope

<?php
function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope.
global $HTTP_POST_VARS;

echo $HTTP_POST_VARS['name'];

// Superglobals are available in any scope and do
// not require 'global'. Superglobals are available
// as of PHP 4.1.0
echo $_POST['name'];
}
?>




با توجه به امکانات شی گرایی موجود ازش استفاده نکنی راحت تری


RTFM
منظور امید راهنمای PHP است.حتما دانلودش کن

http://www.php.net/download-docs.php

Mohammad Minaei
دوشنبه 09 خرداد 1384, 09:22 صبح
من کتاب php4 professional رو گرفتم و توش از این چیزا زیاد استفاده کرده. هر چی هم گشتم توش مطلبی در این مورد پیدا نکردم. فقط بگید چی کار می کنه؟ کتابرو دانلود کرده بودم!

oxygenws
دوشنبه 09 خرداد 1384, 10:51 صبح
لطفا نمونه کد رو اینجا بنویس.

houtanal
دوشنبه 09 خرداد 1384, 15:15 عصر
بهت اجازه میده از یک متغییر در هر جایی استفاده کنی کافیست زمان استفاده کلمه کلیدی global رو پشتت بذاری.کد های بالا رو بخون متوجه میشی

Mohammad Minaei
سه شنبه 10 خرداد 1384, 09:19 صبح
هوتن عزیز ازت خیلی متشکرم!
از آقای راد هم که می خواستن کد من رو بررسی کنن متشکرم! حالا که جواب کامل اومده دیگه زحمت نمی دیم!