I am very new to PHP and am still learning.
I often need to retrieve a specific variable and access its properties.
user_login . "
"); echo('User level: ' . $user_info->user_level . "
"); echo('User ID: ' . $user_info->ID . "
"); echo('Name: ' . $user_info->user_firstname . "
"); echo('Last name: ' . $user_info->user_lastname . "
"); echo('Registration time: ' . $user_info->user_registered . "
"); ?>
I prefer to retrieve$user_info = get_userdata($id); code> and then use it when needed.
user_login; ?> user_login; ?>
But I suspect that $user_info
cannot be shared between blocks since it is not global. What is the usual approach in this situation?
You can use it inside code blocks (loops, conditional statements), but not insidefunctions. If you want to use it inside a function, you need to use the
global
keyword:You can learn more about PHP variable scope in the official documentation :)
You put too much meaning into the php code block.
This is not a global thing.
These blocks belong to the same PHP script. It's just a nice way of outputting HTML and has no other meaning. You can replace it with echo HTML without any difference.
The entire PHP script is executed at once, not in an iterative manner, as you might imagine, think of the PHP block being executed on the server side, then the HTML block being executed on the client side, and then back to the server side to execute the PHP block, So on and so forth. This is wrong.
The entire PHP script is executed on the server side, and the result is displayed in the browser as pure HTML,and then ends.
That's why you can't write both an HTML form and its handler in the same PHP script, just put the latter after the former. Youmust call the serveragain for the handler to work. This will be a completely different call, another instance of the same script,knowing nothing about the previous call, which has long since ended. This is also another thing you must know about PHP:
The execution of PHP scripts is atomic. It's not like a desktop application running continuously in the browser, or even a daemon keeping a persistent connection to the desktop application. It's more like a command line utility - do your job and exit. It runs discretely: