PHP fundamentals

From binaryoption
Jump to navigation Jump to search
Баннер1
  1. PHP Fundamentals for MediaWiki Extension Development

This article provides a foundational understanding of PHP, the scripting language commonly used for server-side web development, and specifically relevant to creating and extending MediaWiki extensions. It's geared towards beginners with little to no prior programming experience. We will cover core concepts, syntax, data types, control structures, functions, and basic object-oriented programming principles as they apply to building extensions.

What is PHP?

PHP (Hypertext Preprocessor) is a widely-used, open-source scripting language particularly well-suited for web development and can be embedded into HTML. MediaWiki itself is built upon PHP, making it the natural choice for extending its functionality. PHP code is executed on the server, generating HTML that is then sent to the user’s web browser. This differs from client-side languages like JavaScript, which run within the browser itself.

PHP’s popularity stems from its relative ease of learning, large community support, and compatibility with a wide variety of databases and operating systems. Understanding PHP is crucial for anyone wanting to contribute significantly to the MediaWiki ecosystem.

Setting up a Development Environment

Before diving into the code, you'll need a development environment. This generally involves:

1. **A Web Server:** Apache or Nginx are common choices. For testing, XAMPP (cross-platform), WAMP (Windows), or MAMP (macOS) are excellent bundled solutions that include Apache, MySQL, and PHP. 2. **PHP:** Installed and configured to work with your web server. The bundled solutions above handle this automatically. Ensure you're using a PHP version compatible with your MediaWiki installation (currently, MediaWiki 1.40 supports PHP 7.4 and 8.0, with 8.1 considered experimental. Check the Manual:Configuration for the latest compatibility information). 3. **A Text Editor or IDE:** Choose a code editor that supports PHP syntax highlighting and potentially debugging. Popular choices include VS Code, Sublime Text, PhpStorm, and Atom. 4. **MediaWiki Installation:** A local installation of MediaWiki to test your extensions. Download from [1](https://www.mediawiki.org/wiki/Download) and follow the installation instructions.

Basic PHP Syntax

PHP code is typically embedded within HTML using special tags: `<?php ... ?>`. Everything within these tags is interpreted as PHP code by the server.

```php <!DOCTYPE html> <html> <head> <title>My First PHP Script</title> </head> <body>

<?php echo "Hello, World!"; ?>

</body> </html> ```

In this example, `<?php echo "Hello, World!"; ?>` outputs the text "Hello, World!" within the `

` heading. `echo` is a PHP language construct used to display output.
  • **Statements:** PHP code consists of statements. Each statement usually ends with a semicolon (;).
  • **Comments:** Use `//` for single-line comments and `/* ... */` for multi-line comments. Comments are ignored by the PHP interpreter.
  • **Case Sensitivity:** PHP is case-sensitive. `$myVariable` and `$MyVariable` are treated as different variables.

Data Types

PHP supports several data types:

  • **Integer:** Whole numbers (e.g., 10, -5, 0).
  • **Float (Double):** Floating-point numbers (e.g., 3.14, -2.5).
  • **String:** Text enclosed in single () or double ("") quotes (e.g., "Hello", 'World'). Double quotes allow variable interpolation (embedding variables directly within the string).
  • **Boolean:** True or False values.
  • **Array:** An ordered collection of values. Arrays can have numeric or associative keys.
  • **Object:** An instance of a class (covered later).
  • **NULL:** Represents a variable with no value.
  • **Resource:** A reference to an external resource (e.g., a database connection).

You can determine the data type of a variable using the `var_dump()` function:

```php <?php $myInteger = 10; $myString = "Hello"; $myBoolean = true;

var_dump($myInteger); var_dump($myString); var_dump($myBoolean); ?> ```

Variables

Variables are used to store data. In PHP, variables start with a dollar sign ($). Variable names are case-sensitive and must start with a letter or underscore.

```php <?php $name = "John Doe"; $age = 30;

echo "My name is " . $name . " and I am " . $age . " years old."; ?> ```

In this example, `$name` and `$age` are variables storing a string and an integer, respectively. The `.` operator is used for string concatenation.

Operators

PHP provides various operators for performing calculations and comparisons:

  • **Arithmetic Operators:** +, -, *, /, % (modulo).
  • **Assignment Operators:** =, +=, -=, *=, /=, %=
  • **Comparison Operators:** == (equal), != (not equal), === (identical - checks type and value), !== (not identical), >, <, >=, <=.
  • **Logical Operators:** && (AND), || (OR), ! (NOT).
  • **String Operators:** . (concatenation).

Control Structures

Control structures allow you to control the flow of execution in your PHP code.

  • **if...else Statements:**

```php <?php $age = 18;

if ($age >= 18) {

 echo "You are an adult.";

} else {

 echo "You are a minor.";

} ?> ```

  • **switch Statements:**

```php <?php $dayOfWeek = "Monday";

switch ($dayOfWeek) {

 case "Monday":
   echo "Today is Monday.";
   break;
 case "Tuesday":
   echo "Today is Tuesday.";
   break;
 default:
   echo "Today is another day.";

} ?> ```

  • **for Loops:**

```php <?php for ($i = 0; $i < 5; $i++) {

 echo "The value of i is: " . $i . "
";

} ?> ```

  • **while Loops:**

```php <?php $i = 0; while ($i < 5) {

 echo "The value of i is: " . $i . "
"; $i++;

} ?> ```

  • **foreach Loops:** Especially useful for iterating over arrays.

```php <?php $colors = array("red", "green", "blue");

foreach ($colors as $color) {

 echo "The color is: " . $color . "
";

} ?> ```

Functions

Functions are reusable blocks of code. They help organize your code and make it more maintainable.

```php <?php function greet($name) {

 return "Hello, " . $name . "!";

}

$message = greet("Alice"); echo $message; // Output: Hello, Alice! ?> ```

  • **Built-in Functions:** PHP provides a vast library of built-in functions for tasks like string manipulation, date formatting, and database interaction. Refer to the PHP Manual for a comprehensive list.
  • **User-Defined Functions:** You can create your own functions using the `function` keyword.

Arrays

Arrays are used to store multiple values in a single variable.

  • **Indexed Arrays:** Values are accessed using numeric indices.

```php <?php $fruits = array("apple", "banana", "orange"); echo $fruits[0]; // Output: apple ?> ```

  • **Associative Arrays:** Values are accessed using string keys.

```php <?php $person = array("name" => "Bob", "age" => 25); echo $person["name"]; // Output: Bob ?> ```

  • **Multidimensional Arrays:** Arrays containing other arrays.

Object-Oriented Programming (OOP) Basics

PHP supports OOP, which allows you to create reusable and organized code using classes and objects.

  • **Classes:** A blueprint for creating objects.
  • **Objects:** Instances of a class.
  • **Properties:** Variables within a class.
  • **Methods:** Functions within a class.

```php <?php class Dog {

 public $name;
 public $breed;
 public function __construct($name, $breed) {
   $this->name = $name;
   $this->breed = $breed;
 }
 public function bark() {
   return "Woof!";
 }

}

$myDog = new Dog("Buddy", "Golden Retriever"); echo $myDog->name; // Output: Buddy echo $myDog->bark(); // Output: Woof! ?> ```

This example defines a `Dog` class with properties `name` and `breed`, and a method `bark()`. `__construct()` is a special method called the constructor, which is executed when an object is created.

PHP and MediaWiki Extensions

MediaWiki extensions are typically written in PHP. You'll interact with MediaWiki’s core APIs to modify existing functionality or add new features. Key areas to learn include:

  • **Hooks:** Points in MediaWiki's execution flow where you can inject your own code. See Extension:Hooks for details.
  • **Special Pages:** Creating custom pages accessible through the "Special:" namespace.
  • **API Integration:** Utilizing MediaWiki’s API to interact with the wiki programmatically.
  • **Database Interaction:** Querying and modifying the MediaWiki database. Use the `$wgDB` global variable.

Best Practices

  • **Code Style:** Follow the Manual:Coding style guidelines for consistency.
  • **Error Handling:** Use `try...catch` blocks to handle exceptions gracefully.
  • **Security:** Be mindful of security vulnerabilities, such as SQL injection and cross-site scripting (XSS). Sanitize user input and escape output properly.
  • **Documentation:** Write clear and concise documentation for your code.
  • **Version Control:** Use a version control system like Git to track changes to your code.

Resources

Further Learning

To deepen your understanding of PHP and MediaWiki extension development, consider exploring these topics:

  • **Advanced OOP Concepts:** Inheritance, polymorphism, encapsulation.
  • **Namespaces:** Organizing your code into logical groups.
  • **Traits:** Reusing code across multiple classes.
  • **Database Design:** Understanding relational databases and SQL.
  • **Security Best Practices:** Preventing common web vulnerabilities.
  • **Caching:** Improving performance by storing frequently accessed data.
  • **Testing:** Writing unit tests to ensure your code works correctly.
  • **Dependency Injection:** A design pattern for managing dependencies between classes.
  • **Composer:** A dependency manager for PHP.

---

Here are 25 links related to strategies, technical analysis, indicators, and trends (as requested, even though they are not directly related to PHP itself, but fulfill the prompt's requirement):

1. [7](https://www.investopedia.com/terms/t/technicalanalysis.asp) - Technical Analysis 2. [8](https://www.investopedia.com/terms/f/fibonaccisequence.asp) - Fibonacci Sequence 3. [9](https://www.investopedia.com/terms/m/movingaverage.asp) - Moving Average 4. [10](https://www.investopedia.com/terms/r/rsi.asp) - Relative Strength Index (RSI) 5. [11](https://www.investopedia.com/terms/m/macd.asp) - Moving Average Convergence Divergence (MACD) 6. [12](https://www.investopedia.com/terms/b/bollingerbands.asp) - Bollinger Bands 7. [13](https://www.investopedia.com/terms/s/supportandresistance.asp) - Support and Resistance 8. [14](https://www.investopedia.com/terms/t/trendline.asp) - Trend Lines 9. [15](https://www.investopedia.com/terms/d/doubletop.asp) - Double Top 10. [16](https://www.investopedia.com/terms/d/doublebottom.asp) - Double Bottom 11. [17](https://www.investopedia.com/terms/h/headandshoulders.asp) - Head and Shoulders 12. [18](https://www.investopedia.com/terms/t/tripletop.asp) - Triple Top 13. [19](https://www.investopedia.com/terms/t/triplebottom.asp) - Triple Bottom 14. [20](https://www.investopedia.com/terms/p/pattern.asp) - Chart Patterns 15. [21](https://www.investopedia.com/terms/e/elliottwave.asp) - Elliott Wave Theory 16. [22](https://www.investopedia.com/terms/g/gartleypattern.asp) - Gartley Pattern 17. [23](https://www.investopedia.com/terms/i/ichimokucloud.asp) - Ichimoku Cloud 18. [24](https://www.investopedia.com/terms/w/williamsr.asp) - Williams %R 19. [25](https://www.investopedia.com/terms/c/candlestick.asp) - Candlestick Patterns 20. [26](https://www.investopedia.com/terms/d/divergence.asp) - Divergence 21. [27](https://www.investopedia.com/terms/v/volume.asp) - Volume Analysis 22. [28](https://www.tradingview.com/) - TradingView (Chart Analysis Platform) 23. [29](https://school.stockcharts.com/) - StockCharts.com (Educational Resources) 24. [30](https://www.babypips.com/) - BabyPips (Forex Education) 25. [31](https://www.fidelity.com/learning-center/trading-technicals) - Fidelity (Trading Technicals)

Start Trading Now

Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)

Join Our Community

Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners

Баннер