search
HomeBackend DevelopmentPHP TutorialStudy Notes on PHP Global Variables_PHP Tutorial

Study Notes on PHP Global Variables_PHP Tutorial

Jul 13, 2016 am 10:49 AM
phpone timeandintroduceoverall situationvariablestudyusunderstandusagenotes

Today we refer to PHP’s official introduction to PHP global variables to understand some uses of PHP global variables and some of our own thoughts on them. I hope it will be helpful to all students by sharing them now.


1. Thinking about the core points:

1. Which global variables are expired and how to deal with them?
For example: unset($GLOBALS, $_ENV, $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_SERVER_VARS, $HTTP_ENV_VARS);
2. Which global variables are invalid on the command line?
3. How to use htmlspecialchars(), why use it?
4. What are the connections and differences between $_REQUEST and $_GET, $_POST, $_COOKIE?
5. Why is the file uploaded but the $_FILES variable does not exist or is empty?
6. What is the scope of global variables?
7. I want to get the user’s IP and browser’s user_agent information. How to get it?
8. I don’t use a browser, am I doing socket programming? How to maintain session?
9. How to obtain header information?


PHP’s nine global predefined arrays

Superglobal variables — Superglobal variables are built-in variables that are always available in all scopes
$GLOBALS — references all variables available in the global scope
$_SERVER — Server and execution environment information
$_GET — HTTP GET variable
$_POST — HTTP POST variable
$_FILES — HTTP file upload variable
$_REQUEST — HTTP Request variable
$_SESSION — Session variable
$_ENV — environment variable
$_COOKIE — HTTP Cookies
$php_errormsg — Previous error message
$HTTP_RAW_POST_DATA — Raw POST data
$http_response_header — HTTP response header
$argc — Number of arguments passed to the script
$argv — Array of arguments passed to the script

2. Main issues
====================================

Summary topic of PHP basics:
1>. var_dump(0=="ads"); What is the result of this statement? Why?
Answer: The result of this statement is true;
The string on the right side of this expression is forced to be converted to int data 0 by default, which is the same as the data on the left side, so true is output. If it is "===", false is output. This is because they have different types and different values. , no coercion is done here.

Comment: It’s hard to say this, let’s test it! var_dump() prints the result of an expression! This actual test is about expression operations.

2>. Can exceptions be cloned?
Answer: No.

3>.What are the characteristics of Traits in PHP?
Answer: Traits (horizontal reuse/multiple inheritance) is a set of methods that are structured like a class, but it cannot be instantiated. It allows developers to easily reuse methods in different classes;
The best application of Traits is that multiple classes can share the same function;
Static variables can be referenced by trait methods, but cannot be defined by the trait. But traits can define static methods for the classes they use;
If a trait defines a property, the class cannot define a property with the same name, otherwise an error will be generated;

Summary: Good questions and good answers

======================================

1. What are the super global variables? Answer: Super global variables: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV

2. The browser has disabled cookies, can $_SESSION still be used? Answer: It can no longer be used
Comment: Wrong answer, it works! Apache has an automatic function to put session_id in the get parameter.

3. Is $php_errormsg available at any time? Answer: No, this variable is only available in the scope where the error occurs, and the track_errors configuration item is required to be turned on (the default is turned off).

Summary: Very positive, it would be better if the answer is more comprehensive

========================================

Personalized interview questions
Write 30 php string functions.
Example:
trim() Remove spaces from string
chop() Deletes the specified character from right to left, parameter rtrim(string,find);
rtrim() Delete the specified character from right to left, parameter rtrim(string,find);
chr() Returns the asc2 code of the character
var_dump() Prints a value, which can be in any form, and returns the value's attributes
print() Print array or string
print_r() simply prints strings and numbers, while arrays are displayed as a bracketed list of keys and values ​​
chunk_split() Split the string into a series of smaller parts
implode() Combines array elements into a string
join() Combines array elements into a string
explode() Split the string into arrays
md5() Returns an md5 value, irreversible
strlen() Get the length of a string
str_replace Replace some characters in the string
mb_substr mb extended interception string function, format: mb_substr(string,start_Num,end_Num,'utf-8')
str_split Split a string into an array according to the character spacing
strpos Find and return the position of the first match
strtr Convert specific characters in the string
substr Intercept the string
substr_count Counts the number of occurrences of a certain character segment in a string
substr_replace Replace some characters in the string
The wordwrap function wraps a string according to the specified length
addcslashes() Adds a backslash
before the specified character strtolower() Convert the string to lowercase
strtoupper() Convert string to uppercase
strrev() Reverse string
strripos() Find the last occurrence of a string in another string (case insensitive)
strrpos() Find the last occurrence of a string in another string (case sensitive)
strspn() Returns the number of specific characters contained in the string
ucwords() Converts the first character of each word in the string to uppercase
str_repeat() Repeat the string the specified number of times
...

========================================

1. Does the namespace have to be the first statement of the program script?
Answer: yes

2. How to cancel the reference?
Answer: unset();

3. If at least one method in a class is declared abstract, does this class have to be declared abstract? When inheriting an abstract class, does the subclass have to define all abstract methods in the parent class?
Answer: If there are abstract methods in a class, the class must be defined as an abstract class. When inheriting an abstract class, the subclass must define all abstract methods in the parent class.

========================================

1. How to get the absolute path of the file
Use the realpath() function to return the absolute path name. If it fails, it returns false, for example the file does not exist.
echo realpath("test.txt");
Output:
C:wwwtestwebtest.txt

2. How session works
The session is saved on the server, but a sessionid is saved on the client in the form of a cookie. If cookies are disabled, you need to use the URL rewriting mechanism of the get method or use the POST method to submit a hidden form.

Comments: This is the principle, but generally a web server will automatically complete this function, and there is no need to add it in the program.

3. Is the function declared by public static a static method?
The function declared by public static is a static method and can be used directly outside the class. The method call of class name::function name does not need to be declared in the NEW way
Note: There cannot be dynamic content within the function such as $this->
Generally speaking, content that needs to be executed frequently is declared with STATIC

Summary: The working principle of session is well organized and analyzed thoroughly. I hope to be more positive in the future and continue to work hard

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632673.htmlTechArticleToday we refer to PHP’s official introduction to PHP global variables to understand some usage of PHP global variables and some of our own opinions on them Think about it and share it now. I hope it will be helpful to all students. One...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor