← PHP EnglishChapter 02 of 13

Variables and Data Types

## Learning Objectives - Declare and use variables - Understand PHP data types - Master type juggling and casting - Work with constants ## Variables ### Declaration and Assignment ```php ``` ### Variable Variables ```php ``` ### References ```php ``` ## Data Types ### Scalar Types #### Integer ```php ``` #### Float (Double) ```php ``` #### String ```php ``` #### Boolean ```php ``` ### Compound Types #### Array ```php "Alice", "age" => 25]; $mixed = ["text", 123, true, 3.14]; ?> ``` #### Object ```php name = "Alice"; $person->age = 25; ?> ``` ### Special Types #### NULL ```php ``` #### Resource ```php ``` ## Type Juggling PHP automatically converts types based on context: ```php ``` ### Type Conversion Table | Original Type | To Int | To Float | To String | To Bool | |---------------|--------|----------|-----------|---------| | "10" | 10 | 10.0 | "10" | true | | "" | 0 | 0.0 | "" | false | | "hello" | 0 | 0.0 | "hello" | true | | -10 | -10 | -10.0 | "-10" | true | | 0 | 0 | 0.0 | "0" | false | | null | 0 | 0.0 | "" | false | ## Type Casting ### Explicit Casting ```php ``` ### Cast to Array/Object ```php ``` ### settype() ```php ``` ## Type Checking Functions ```php ``` ## Constants ### define() ```php "localhost", "db_name" => "mydb" ]); echo CONFIG["db_host"]; // localhost ?> ``` ### const Keyword ```php ``` ### Difference: define vs const ```php ``` ### Magic Constants ```php ``` ## Variable Scope ### Local Scope ```php ``` ### Global Scope ```php ``` ### $GLOBALS Array ```php ``` ### Static Variables ```php ``` ## Summary - Variables start with `$` (e.g., `$name`) - PHP has 8 data types: int, float, string, bool, array, object, resource, NULL - Type juggling: PHP converts types automatically - Use `(type)` for explicit casting: `(int)`, `(float)`, `(string)`, `(bool)` - `define()` and `const` for constants - Magic constants: `__FILE__`, `__LINE__`, `__DIR__`, etc. - Variables have local scope by default - Use `global` or `$GLOBALS` to access global variables - `static` variables retain value between function calls

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →