美文网首页
PHP-变量

PHP-变量

作者: hellowenqi | 来源:发表于2017-03-14 00:13 被阅读28次

基本变量

$开头,紧跟一个字母或者下划线,之后再跟不限数量的字母、数字、下划线;正则表达为:

[a-zA-Z_\x7f-\xff][0-9a-zA-Z_\x7f-\xff]*

最好初始化变量,未初始化的变量在使用的时候根据上下文取初始值。如boolean环境为false; int 为0;float 为0.0;string 为""; array为空数组;对象为空对象;

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

预定义变量

下面罗列大写字母的为超全局变量,在任何地方都可以访问;不是大写的是一般的全局变量,在函数内部不能访问。

$GLOBALS 访问文件中的全局变量

function test(){
  $foo = "i am fool";
  echo "access global {$GLOBALS['foo']}\n";   //access global  global foo
  echo "access local {$foo}\n";   //access local i am fool
}
$foo = " global foo";

$_GET 用户GET方法请求的数组
$_POST 用户POST方法请求的数组
$_REQUEST GET 和 POST 方法请求的数组
$_FILES POST方法上传的文件,仅此一个复数形式
$_SERVER 包括了整个请求的信息

用户请求相关,(个人觉的是浏览器发送的请求头中的信息)
HTTP_HOST  用户请求的主机名(域名或者是IP,在浏览器中输入的)
HTTP_ACCEPT 用户可以接受的文件类型
HTTP_ACCEPT_ENCODING 用户可接收的的压缩编码格式
HTTP_ACCEPT_LANGUAGE 用户可以理解的语言
HTTP_USER_AGENT 请求客户端信息
HTTP_COOKIE 请求携带的cookie
//用户请求
REQUEST_METHOD 请求使用的方法
REQUEST_SCHEME 请求的协议 http还是https
REQUEST_URI 请求地址中端口号后面所有的字符串,包括参数
QUERY_STRING GET方法中的参数
REMOTE_ADDR 请求侧的IP,不是私有地址,感觉应该是出口IP地址
REMOTE_PORT 同上,应该是出口端口号
//服务器相关
SERVER_SOFTWARE 服务器的信息
SERVER_ADDR 服务器的IP地址
SERVER_PORT 服务器端的端口号,一般为80
SCRIPT_FILENAME 放问的文件的在服务器的绝对路径
DOCUMENT_ROOT 域名所指向的根路径
下面是完整参考
array(33) {
  ["UNIQUE_ID"]=>
  string(27) "WMardfubhCEAZytbSVp3sAAAAAE"
  ["HTTP_HOST"]=>
  string(14) "h5app.7dyk.com"
  ["HTTP_CONNECTION"]=>
  string(10) "keep-alive"
  ["HTTP_CACHE_CONTROL"]=>
  string(9) "max-age=0"
  ["HTTP_UPGRADE_INSECURE_REQUESTS"]=>
  string(1) "1"
  ["HTTP_USER_AGENT"]=>
  string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
  ["HTTP_ACCEPT"]=>
  string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
  ["HTTP_ACCEPT_ENCODING"]=>
  string(19) "gzip, deflate, sdch"
  ["HTTP_ACCEPT_LANGUAGE"]=>
  string(14) "zh-CN,zh;q=0.8"
  ["HTTP_COOKIE"]=>
  string(123) "CNZZDATA1259969345=692633714-1478100153-%7C1479091446; _ga=GA1.2.678844300.1478100268; PHPSESSID=ri7l2mcvoc3ottu14dde1mv4e5"
  ["PATH"]=>
  string(49) "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
  ["SERVER_SIGNATURE"]=>
  string(0) ""
  ["SERVER_SOFTWARE"]=>
  string(52) "Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips PHP/5.4.16"
  ["SERVER_NAME"]=>
  string(14) "h5app.7dyk.com"
  ["SERVER_ADDR"]=>
  string(14) "101.200.85.218"
  ["SERVER_PORT"]=>
  string(2) "80"
  ["REMOTE_ADDR"]=>
  string(13) "114.255.40.10"
  ["DOCUMENT_ROOT"]=>
  string(13) "/var/www/html"
  ["REQUEST_SCHEME"]=>
  string(4) "http"
  ["CONTEXT_PREFIX"]=>
  string(0) ""
  ["CONTEXT_DOCUMENT_ROOT"]=>
  string(13) "/var/www/html"
  ["SERVER_ADMIN"]=>
  string(16) "wuwenqi@7dyk.com"
  ["SCRIPT_FILENAME"]=>
  string(26) "/var/www/html/ama/test.php"
  ["REMOTE_PORT"]=>
  string(5) "30255"
  ["GATEWAY_INTERFACE"]=>
  string(7) "CGI/1.1"
  ["SERVER_PROTOCOL"]=>
  string(8) "HTTP/1.1"
  ["REQUEST_METHOD"]=>
  string(3) "GET"
  ["QUERY_STRING"]=>
  string(8) "name=123"
  ["REQUEST_URI"]=>
  string(22) "/ama/test.php?name=123"
  ["SCRIPT_NAME"]=>
  string(13) "/ama/test.php"
  ["PHP_SELF"]=>
  string(13) "/ama/test.php"
  ["REQUEST_TIME_FLOAT"]=>
  float(1489415029.184)
  ["REQUEST_TIME"]=>
  int(1489415029)
}

$_SESSION PHP默认的session机制中,session数据
$_COOKIE 用户请求携带的coockie信息
php://input 消息体中原始数据

<?php $postdata = file_get_contents("php://input"); ?> 
php://input is not available with enctype="multipart/form-data"

$http_response_headers : 返回消息头,与get_headers(string $url)功能一样

<?php
function get_contents() {
  file_get_contents("http://example.com");
  var_dump($http_response_header);
}
array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

argv 命令行模式,参数的数组, argv[0]为 脚本名
argc 命令行模式,参数的个数,最小值位1,因为脚本名被认为是第一个参数

变量作用域

全局变量

在PHP文件最外层的变量拥有全局作用域,同样作用于include和require文件

<?php
$a = 1;
include 'b.inc';    //b文件中也可以访问$a
?>
函数局部作用域

函数中的变量的作用域仅在函数中,比较严格,内部不能访问外部的全局变量,如果想要访问,需要使用 global 关键字或者是使用超全局变量 $GLOBALS;

<?php
$a = 1;
$b = 2;
function Sum()
{
    global $a, $b;
    $b = $a + $b;   //这两句可以替换为 $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
} 
Sum();
echo $b;  //输出3
?>
static 变量

static 仅能存在于函数局部作用域中,变量只在编译的时候初始化一次,且函数执行后的值仍然保留。static 和 global 都是通过引用实现的

变量的变量

一个变量的值作为另一个变量的名称;用在变量的声明,也可用在对象的属性中,为消除语义分歧,使用{}

<?php

  //You can even add more Dollar Signs

  $Bar = "a";
  $Foo = "Bar";
  $World = "Foo";
  $Hello = "World";
  $a = "Hello";

  $a; //Returns Hello
  $$a; //Returns World
  $$$a; //Returns Foo
  $$$$a; //Returns Bar
  $$$$$a; //Returns a

  $$$$$$a; //Returns Hello
  $$$$$$$a; //Returns World

  //... and so on ...//
?>

常量的定义

类外部定义使用 define("MAX_NUMBER", 10); 5.3以后可以也可以使用const定义,名称区分大小写。
类内部定义使用 const MAX_NUMBER = 10;

class test{
  const MAX_NUMBER = 10;
  function print(){
    echo self::MAX_NUMBER;   //类内部函数调用
  }  
}
echo Test::MAX_NUMBER; 外部访问类的常量

get_defined_constants(boolean categorize) //获取到所有定义的常量,一般category为true,得到的是多维数组,用户定义的在 $constants['user']分类中。

<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>

输出:

Array
(
    [Core] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

魔法变量

魔法变量在编译时候初始化(即使是根据代码中的位置决定的),而一般的常量在运行时初始化,下表为9个魔法变量,不区分大小写:

名称 描述
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ The function name.
__CLASS__ The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 CLASS works also in traits. When used in a trait method, CLASS is the name of the class the trait is used in.
__TRAIT__ The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name.
__NAMESPACE__ The name of the current namespace.
ClassName::class The fully qualified class name. See also ::class. 5.5版本以后才可以使用。

相关文章

  • 第3章 PHP变量

    PHP-什么是变量 变量是用于存储值的 PHP-如何定义变量 定义变量就是向服务器的内存(服务器的内存,我们可以当...

  • PHP-变量

    基本变量 $开头,紧跟一个字母或者下划线,之后再跟不限数量的字母、数字、下划线;正则表达为: 最好初始化变量,未初...

  • PHP-引用变量

    1.&引用变量 2.zval变量容器 3.注意点 EX ex1: ex2:

  • php入门知识点

    1、PHP-变量名的命名规则 2、通过使用“memory_get_usage”获取当前PHP消耗的内存 3、var...

  • idea代码格式对齐

    setting->Editor->Code Style->PHP->wrapping and braces Ass...

  • php 各扩展安装

    http://www.php.net/distributions/php-$version.tar.gz bcmath

  • swoole笔记03(搭建http服务器)

    常规: http请求从nginx->fast-cgi->php->返回给前端用户 (fpm) swoole ...

  • Laravel-5-8学习

    title: Laravel-5.8学习date: 2019-05-13 14:07:10tags:- PHP- ...

  • PHP    GD2问题:Fatal error: Call t

    1.开打wamp,左击->PHP->进入php.ini,将;extention=php_gd2.dll前面的分号(...

  • 2.php之静态绑定

    http://www.godblessyuan.com/2016/05/30/php-%E5%90%8E%E6%9...

网友评论

      本文标题:PHP-变量

      本文链接:https://www.haomeiwen.com/subject/vngxnttx.html