php类 静态变量赋值 static $name="abc"

本文深入解析了PHP中静态属性的实现原理,详细介绍了如何通过PHP语法定义静态属性,并且跟踪了从定义到获取整个过程中涉及的关键步骤和技术细节。

 

<?php
class test
{
   static $name="abc";
}

echo test::$name;

 

1.巴斯科范式

 

class_statement:
        variable_modifiers { CG(access_type) = Z_LVAL($1.u.constant); } class_variable_declaration ';'
;

member_modifier:
        T_PUBLIC                { Z_LVAL($$.u.constant) = ZEND_ACC_PUBLIC; }
    |    T_PROTECTED                { Z_LVAL($$.u.constant) = ZEND_ACC_PROTECTED; }
    |    T_PRIVATE                { Z_LVAL($$.u.constant) = ZEND_ACC_PRIVATE; }
    |    T_STATIC                { Z_LVAL($$.u.constant) = ZEND_ACC_STATIC; }
    |    T_ABSTRACT                { Z_LVAL($$.u.constant) = ZEND_ACC_ABSTRACT; }
    |    T_FINAL                    { Z_LVAL($$.u.constant) = ZEND_ACC_FINAL; }
;

class_variable_declaration:
        class_variable_declaration ',' T_VARIABLE                    { zend_do_declare_property(&$3, NULL, CG(access_type) TSRMLS_CC); }
    |    class_variable_declaration ',' T_VARIABLE '=' static_scalar    { zend_do_declare_property(&$3, &$5, CG(access_type) TSRMLS_CC); }
    |    T_VARIABLE                        { zend_do_declare_property(&$1, NULL, CG(access_type) TSRMLS_CC); }
    |    T_VARIABLE '=' static_scalar    { zend_do_declare_property(&$1, &$3, CG(access_type) TSRMLS_CC); }
;

variable:
    T_STRING T_PAAMAYIM_NEKUDOTAYIM base_variable { $$ = $3; zend_do_fetch_static_member(&$$, &$1 TSRMLS_CC); }
;

base_variable:
    T_VARIABLE            {  fetch_simple_variable(&$$, &$1, 1 TSRMLS_CC); }    
;

 

 

 

 

 

理解版

class_statement:
        variable_modifiers { CG(access_type) = Z_LVAL($1.u.constant); } class_variable_declaration ';'
;

member_modifier:
        T_PUBLIC                { Z_LVAL($$.u.constant) = ZEND_ACC_PUBLIC; }
    |    T_PROTECTED                { Z_LVAL($$.u.constant) = ZEND_ACC_PROTECTED; }
    |    T_PRIVATE                { Z_LVAL($$.u.constant) = ZEND_ACC_PRIVATE; }
    |    T_STATIC                { Z_LVAL($$.u.constant) = ZEND_ACC_STATIC; }
    |    T_ABSTRACT                { Z_LVAL($$.u.constant) = ZEND_ACC_ABSTRACT; }
    |    T_FINAL                    { Z_LVAL($$.u.constant) = ZEND_ACC_FINAL; }
;

class_variable_declaration:
        class_variable_declaration ',' T_VARIABLE                    { zend_do_declare_property(&$3, NULL, CG(access_type) TSRMLS_CC); }
    |    class_variable_declaration ',' T_VARIABLE '=' static_scalar    { zend_do_declare_property(&$3, &$5, CG(access_type) TSRMLS_CC); }
    |    T_VARIABLE                        { zend_do_declare_property(&$1, NULL, CG(access_type) TSRMLS_CC); }
    |    T_VARIABLE '=' static_scalar    { zend_do_declare_property(&$1, &$3, CG(access_type) TSRMLS_CC); }
;

variable:
    T_STRING T_PAAMAYIM_NEKUDOTAYIM T_VARIABLE { $$ = $3; zend_do_fetch_static_member(&$$, &$1 TSRMLS_CC); }
;

 

 

2.对于 static $name="abc" 

组织propert_info结构体,将其存于为类中的property_info 这个HashTable中,

注意: value 这个值是存在类中的property_table中,其中key 为property_info中的offset

void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */
{
    zval *property;
    ALLOC_ZVAL(property);
    if (value) {
        *property = value->u.constant;
    } else {
        INIT_PZVAL(property);
        Z_TYPE_P(property) = IS_NULL;
    }
    zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(Z_STRVAL(var_name->u.constant), Z_STRLEN(var_name->u.constant) + 1, 0 TSRMLS_CC), Z_STRLEN(var_name->u.constant), property, access_type, comment, comment_len TSRMLS_CC);
}

 

ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */
{
    zend_property_info property_info, *property_info_ptr;
    const char *interned_name;
    ulong h = zend_get_hash_value(name, name_length+1);

    if (access_type & ZEND_ACC_STATIC) {
        //如果是静态成员变量,就使用relloc分配需要的内存,size(zval*)*ce->default_static_member_count是总共的内存
        property_info.offset = ce->default_static_members_count++;
        ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS);
        
        ce->default_static_members_table[property_info.offset] = property;
        if (ce->type == ZEND_USER_CLASS) {
            ce->static_members_table = ce->default_static_members_table;
        }
    } else {
        property_info.offset = ce->default_properties_count++;
        ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS);
        ce->default_properties_table[property_info.offset] = property;
    }

    interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC);
    if (interned_name != property_info.name) {
        if (ce->type == ZEND_USER_CLASS) {
            efree((char*)property_info.name);
        } else {
            free((char*)property_info.name);
        }
        property_info.name = interned_name;
    }

    property_info.flags = access_type;
    property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1);

    property_info.ce = ce;
    zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL);
    return SUCCESS;
}

 

 

 

void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */
{
    znode class_node;
    zend_llist *fetch_list_ptr;
    zend_llist_element *le;
    zend_op *opline_ptr;
    zend_op opline;

    zend_do_fetch_class(&class_node, class_name TSRMLS_CC);
    
    if (result->op_type == IS_CV) {
        init_op(&opline TSRMLS_CC);

        opline.opcode = ZEND_FETCH_W;
        opline.result_type = IS_VAR;
        opline.result.var = get_temporary_variable(CG(active_op_array));
        opline.op1_type = IS_CONST;

//opline->op1为 成员变量的值,result->u.op.var为fetch_simple_variable所获得的值 LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)
->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant);

//class_node.op_type此时为IS_VAR
if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); }

 

zend_do_fetch_class 函数的运行

static int ZEND_FASTCALL  ZEND_FETCH_CLASS_SPEC_CONST_HANDLER(ZEND_OPCODE_HANDLER_ARGS)
{
    USE_OPLINE
    zval *class_name = opline->op2.zv;
    if (CACHED_PTR(opline->op2.literal->cache_slot)) {
        EX_T(opline->result.var).class_entry = CACHED_PTR(opline->op2.literal->cache_slot);
    } else {
        EX_T(opline->result.var).class_entry = zend_fetch_class_by_name(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), opline->op2.literal + 1, opline->extended_value TSRMLS_CC);
        CACHE_PTR(opline->op2.literal->cache_slot, EX_T(opline->result.var).class_entry);
//记住 这里被缓存住了
} }

 

 

static int ZEND_FASTCALL zend_fetch_var_address_helper_SPEC_VAR_CONST(int type, ZEND_OPCODE_HANDLER_ARGS)
{
    USE_OPLINE
    zend_free_op free_op1;
    zval *varname;
    zval **retval;

    SAVE_OPLINE();
    varname = _get_zval_ptr_var(opline->op1.var, execute_data, &free_op1 TSRMLS_CC);

    zend_class_entry *ce;
    ce = CACHED_PTR(opline->op2.literal->cache_slot);
    retval = zend_std_get_static_property(ce, Z_STRVAL_P(varname), Z_STRLEN_P(varname), 0, ((IS_VAR == IS_CONST) ? opline->op1.literal : NULL) TSRMLS_CC);    
    
}

 

 

 找到成员变量

ZEND_API zval **zend_std_get_static_property(zend_class_entry *ce, const char *property_name, int property_name_len, zend_bool silent, const zend_literal *key TSRMLS_DC) /* {{{ */
{
    zend_property_info *property_info;
    ulong hash_value;

    
    hash_value = zend_hash_func(property_name, property_name_len+1);
        
   //即使这里的类是子类,子类的ce->properties_info的数据复制于父类的properties_info这个hash table
    if (UNEXPECTED(zend_hash_quick_find(&ce->properties_info, property_name, property_name_len+1, hash_value, (void **) &property_info)==FAILURE)) {
        if (!silent) {
            zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name);
        }
        return NULL;
    }


    if (UNEXPECTED(!zend_verify_property_access(property_info, ce TSRMLS_CC))) {
        if (!silent) {
            zend_error_noreturn(E_ERROR, "Cannot access %s property %s::$%s", zend_visibility_string(property_info->flags), ce->name, property_name);
        }
        return NULL;
    }

    if (UNEXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0)) {
        if (!silent) {
            zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name);
        }
        return NULL;
    }

    if (UNEXPECTED(CE_STATIC_MEMBERS(ce) == NULL) ||
        UNEXPECTED(CE_STATIC_MEMBERS(ce)[property_info->offset] == NULL)) {
        if (!silent) {
            zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name);
        }
        return NULL;
    }
    
    return &CE_STATIC_MEMBERS(ce)[property_info->offset];
}

 

 

 

 

 

转载于:https://www.cnblogs.com/taek/p/4298097.html

PS C:\Users\Administrator> # 加载必要程序集 PS C:\Users\Administrator> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop PS C:\Users\Administrator> PS C:\Users\Administrator> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression >> ) >> >> $resultTemplate = [PSCustomObject]@{ >> StatusCode = 0 >> StatusMessage = "NotExecuted" >> Headers = [ordered]@{} >> Content = $null >> IsSuccess = $false >> Technology = "None" >> ErrorMessage = $null >> ElapsedMs = 0 >> } >> >> $timer = [System.Diagnostics.Stopwatch]::StartNew() >> $result = $resultTemplate.PSObject.Copy() >> $result.Technology = "HttpClient" >> >> $handler = $null >> $client = $null >> $request = $null >> $response = $null >> $originalCallback = $null >> >> try { >> # 创建 HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> >> # 修复证书验证 - 使用全局设置方案 >> if ($SkipCertificateCheck) { >> $originalCallback = [System.Net.ServicePointManager]::ServerCertificateValidationCallback >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> } >> >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建 HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> >> # 设置超时时间(确保有效) >> if ($Timeout -gt 0) { >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> } >> else { >> $client.Timeout = [System.TimeSpan]::FromSeconds(30) >> } >> >> # 创建请求方法对象(兼容方式) >> try { >> $httpMethod = [System.Net.Http.HttpMethod]::new($Method) >> } >> catch { >> $httpMethod = New-Object System.Net.Http.HttpMethod -ArgumentList $Method >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage($httpMethod, $Uri) >> >> # 添加默认 User-Agent >> if (-not $Headers.ContainsKey('User-Agent')) { >> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0") >> } >> >> # 添加自定义头 >> foreach ($key in $Headers.Keys) { >> if (-not $request.Headers.TryAddWithoutValidation($key, $Headers[$key])) { >> if (-not $request.Content) { >> $request.Content = New-Object System.Net.Http.StringContent("") >> } >> $request.Content.Headers.TryAddWithoutValidation($key, $Headers[$key]) >> } >> } >> >> # 处理请求体 >> if ($Body -and @('POST','PUT','PATCH') -contains $Method) { >> if ($Body -is [byte[]]) { >> $request.Content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> elseif ($Body -is [hashtable] -or $Body -is [System.Collections.IDictionary]) { >> $jsonBody = $Body | ConvertTo-Json -Depth 5 -Compress >> $request.Content = New-Object System.Net.Http.StringContent( >> $jsonBody, >> [System.Text.Encoding]::UTF8, >> "application/json" >> ) >> } >> elseif ($Body -is [string]) { >> $request.Content = New-Object System.Net.Http.StringContent( >> $Body, >> [System.Text.Encoding]::UTF8 >> ) >> } >> else { >> throw "Unsupported body type: $($Body.GetType().Name)" >> } >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 解析响应 >> $result.StatusCode = [int]$response.StatusCode >> $result.StatusMessage = $response.ReasonPhrase >> $result.IsSuccess = $response.IsSuccessStatusCode >> >> $result.Headers = [ordered]@{} >> foreach ($header in $response.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> foreach ($header in $response.Content.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> $result.Content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> return $result >> } >> catch [System.Threading.Tasks.TaskCanceledException] { >> $result.ErrorMessage = "Request timed out after $Timeout seconds" >> $result.StatusCode = 408 >> $result.StatusMessage = "Timeout" >> return $result >> } >> catch [System.Net.Http.HttpRequestException] { >> # 处理特定HTTP请求异常 >> $ex = $_.Exception >> $result.ErrorMessage = $ex.ToString() >> >> # 检查内部异常是否为SocketException(DNS解析错误) >> if ($ex.InnerException -is [System.Net.Sockets.SocketException]) { >> $result.StatusCode = 0 >> $result.StatusMessage = "DNSResolutionFailed" >> } >> else { >> $result.StatusCode = 500 >> $result.StatusMessage = "HttpRequestError" >> } >> >> return $result >> } >> catch { >> # 通用错误处理 >> $result.ErrorMessage = $_.Exception.ToString() >> $result.StatusCode = 500 >> $result.StatusMessage = "InternalError" >> return $result >> } >> finally { >> $timer.Stop() >> $result.ElapsedMs = $timer.ElapsedMilliseconds >> >> # 安全清理资源 >> if ($response -is [IDisposable]) { $response.Dispose() } >> if ($request -is [IDisposable]) { $request.Dispose() } >> if ($client -is [IDisposable]) { $client.Dispose() } >> if ($handler -is [IDisposable]) { $handler.Dispose() } >> >> # 恢复全局证书验证设置 >> if ($SkipCertificateCheck -and $null -ne $originalCallback) { >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $originalCallback >> } >> } >> } >> PS C:\Users\Administrator> # 创建模块目录 PS C:\Users\Administrator> $moduleDir = "$env:ProgramFiles\WindowsPowerShell\Modules\PSHttpClient" PS C:\Users\Administrator> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 保存模块文件 PS C:\Users\Administrator> @' >> # 将上面完整的函数代码复制到这里 >> '@ | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 创建模块清单 PS C:\Users\Administrator> New-ModuleManifest -Path "$moduleDir\PSHttpClient.psd1" ` >> -RootModule "PSHttpClient.psm1" ` >> -Author "YourName" ` >> -ModuleVersion "1.0" ` >> -Description "Enhanced HTTP Client for PowerShell" >> PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force -PassThru ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 1.0 PSHttpClient PS C:\Users\Administrator> # 测试自签名证书网站 PS C:\Users\Administrator> $result = Invoke-EnhancedCurlRequest -Uri "https://self-signed.badssl.com/" -SkipCertificateCheck PS C:\Users\Administrator> PS C:\Users\Administrator> if ($result.IsSuccess) { >> Write-Host "✅ 自签名证书网站访问成功" -ForegroundColor Green >> $result.Headers >> } else { >> Write-Host "❌ 自签名证书网站访问失败: $($result.ErrorMessage)" -ForegroundColor Red >> } >> ❌ 自签名证书网站访问失败: System.Net.Http.HttpRequestException: 发送请求时出错。 ---> System.Net.WebException: 基础连接已经关闭: 发送时发生错误。 ---> System.Management.Automation.PSInvalidOperationException: 此线程中没有可用于运行脚本的运行空间。你可以在 System.Management.Automation.Runspaces.Runspace 型的 DefaultRunspace 属性中提供一个运行空间。你尝试调用的脚本块为: ...ue 在 System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) 在 System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) --- 内部异常堆栈跟踪的结尾 --- 在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在 System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- 内部异常堆栈跟踪的结尾 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 CallSite.Target(Closure , CallSite , Object ) PS C:\Users\Administrator> # 测试无效域名 PS C:\Users\Administrator> $result = Invoke-EnhancedCurlRequest -Uri "https://invalid.domain.abc/" PS C:\Users\Administrator> PS C:\Users\Administrator> if ($result.StatusCode -eq 0) { >> Write-Host "✅ DNS错误处理成功" -ForegroundColor Green >> } else { >> Write-Host "❌ DNS错误处理失败: $($result.StatusCode)" -ForegroundColor Red >> } >> ❌ DNS错误处理失败: 500 PS C:\Users\Administrator> # 测试正常网站 PS C:\Users\Administrator> $result = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/get" PS C:\Users\Administrator> PS C:\Users\Administrator> if ($result.IsSuccess) { >> Write-Host "✅ 正常网站访问成功" -ForegroundColor Green >> $result.Content | ConvertFrom-Json >> } else { >> Write-Host "❌ 正常网站访问失败: $($result.ErrorMessage)" -ForegroundColor Red >> } >> ❌ 正常网站访问失败: System.Net.Http.HttpRequestException: 发送请求时出错。 ---> System.Net.WebException: 基础连接已经关闭: 发送时发生错误。 ---> System.Management.Automation.PSInvalidOperationException: 此线程中没有可用于运行脚本的运行空间。你可以在 System.Management.Automation.Runspaces.Runspace 型的 DefaultRunspace 属性中提供一个运行空间。你尝试调用的脚本块为: ...ue 在 System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) 在 System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) --- 内部异常堆栈跟踪的结尾 --- 在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在 System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- 内部异常堆栈跟踪的结尾 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 CallSite.Target(Closure , CallSite , Object ) PS C:\Users\Administrator> # 测试POST请求 PS C:\Users\Administrator> $postData = @{ >> name = "John Doe" >> email = "john@example.com" >> } >> $result = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/post" -Method POST -Body $postData >> PS C:\Users\Administrator> if ($result.IsSuccess) { >> Write-Host "✅ POST请求成功" -ForegroundColor Green >> ($result.Content | ConvertFrom-Json).json >> } else { >> Write-Host "❌ POST请求失败: $($result.StatusCode)" -ForegroundColor Red >> } >> ❌ POST请求失败: 500 PS C:\Users\Administrator>
08-17
任务描述 本关要求学生了解Java中常量和变量的定义,然后实现常量和变量的赋值。 相关知识 常量在程序运行时,不会被修改的量。相应的,变量就是在运行中发生改变的量。 #####变量 变量,顾名思义,就是内容可以改变的量,它与常量相对应。从变量的作用域来定义,可将Java中的变量划分成以下三变量、实例变量和局部变量。 public class HelloWorld{ static int count=0; // 变量 String str="hello world"; // 实例变量 public void method(){ int i =0; // 局部变量 } } 变量 归属的变量,它是通过在定义的属性时,独立于方法之外的变量,用 static 修饰,所以又称为静态变量。 实例变量 归属于的实例的变量,又称为成员变量,独立于方法之外的变量,没有经过static修饰。 不管是变量,还是实例变量,都可以设置Java的访问修饰符,若是需要公开操作,你可以在这些变量前面添加public访问权限;若是只限于所在中操作,你可以在这些变量前面添加private访问权限。 局部变量 在中方法体里面所定义的变量,不管是方法的形参,还是方法体内所定义的变量都是局部变量。局部变量的作用域是以其所在方法体的头大括号开始到尾大括号结束。 #####变量声明与赋值 在Java编码规范中,变量作为一种标识符,应该符合以下规范: 标识符可以由字母,数字,下划线——,美元$组成,但是不能包含@,%,空格等其他的特殊符号,同时,标识符首字母不能以数字开头,例如123name就是不合法的,_abc、$d12、df是可以的; 标识符不能是Java关键字和保留字,但可以包含关键字和保留字,例如:不可以使用for作为标识符,但是for1可以; 标识符是严格区分大小写的,这里myName和myname是两个不同的标识符; 标识符的命名尽量简短且能清楚的表达变量的作用,做到见名知意。如:定义变量名stuName保存“学生姓名”信息。 变量名由多单词组成时,第一个单词的首字母小写,其后单词的首字母大写,俗称骆驼式命名法(也称驼峰命名法),如:myAge 变量命名时,变量的语法格式如下: 先声明后赋值: //声明:变量数据型 变量名 int var; //赋值:变量名 = 指 var = 20; 一步完成声明、赋值: //变量数据型 变量名 = 值 int var = 20; 对于多个变量的初始化,同样可以一步完成 int var1 = 20, var2 = 30; 常量 常量代表程序运行过程中不能改变的值。 常量在程序运行过程中主要有2个作用: 代表常数,便于程序的修改(例如:圆周率的值) 增强程序的可读性(例如:常量UP、DOWN、LEFT和RIGHT分别代表上下左右,其数值分别是1、2、3和4) 常量的语法格式和变量型,只需要在变量的语法格式前面添加关键字final即可。在Java编码规范中,要求常量名必须大写。则常量的语法格式如下: final 数据型 常量名称 = 值; final 数据型 常量名称1 = 值1, 常量名称2 = 值2,…常量名称n = 值n; 例如: final double PI = 3.14; final char MALE=‘M’,FEMALE=‘F’; ####常量表示示例 十六进制整型常量:以十六进制表示时,需以0x或0X开头,如0xff,0X9A。 八进制整型常量:八进制必须以0开头,如0123,034。 长整型:长整型必须以L作结尾,如9L,342L。 浮点数常量:由于小数常量的默认型是double型,所以float型的后面一定要加f或F。同样带小数的变量默认为double型。 f=1.3f;//必须声明f 字符常量:字符型常量需用两个单引号括起来(注意字符串常量是用两个双引号括起来)。Java中的字符占2个字节。一些常用的转义字符: 转义字符 含义 \r 接受键盘输入,相当于按下了回车键 \n 换行 \t 制表符,相当于Tab键 \b 退格键,相当于Back Space键 ' 单引号 '' 双引号 \ 一个斜杠\ 编程要求 本关的编程任务是补全chapter1/step2/Area.java文件中main()函数,声明一个常量PI的值为3.14,变量radius为2,计算半径为2的圆面积并输出语句The area of the circle is 12.56. 本关
最新发布
09-15
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值