Table of Contents
Syntax
Types of PHP Annotations
1. Built-in Annotations
2. Meta Annotations
3. Custom Annotations
Examples of PHP Annotations
Example #3
Conclusion

PHP Annotations

Aug 29, 2024 pm 01:02 PM
php

PHP annotations are basically metadata which can be included in the source code and also in between classes, functions, properties and methods. They are to be started with the prefix @ wherever they are declared and they indicate something specific. This information they provide is very useful to coders, helpful for documentation purposes and also an IDE may use this to display certain popup hint kind of things. The same annotation can also be used for other purposes besides validation such as to determine what kind of input needs to be given in a form and also for automation purposes. There are various kinds of annotations like the @var and @int types which can be used for specific uses as their name itself suggests.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

PHP annotations are used by giving @ prefix and its syntax is as follows:

class Example
{
// @var integer
public $new;
}
Copy after login

Annotation is @var here and whenever it is encountered just before the piece of any code (public $new here for example) it indicates that the $new is to have a value of type integer as told by the annotation.

class Example
{
// @var integer
// @range(0, 51)
// @label('Count of shops')
public $shop;
}
Copy after login

Annotations can also be used for specifying the range where it displays the maximum and the minimum values that are to be accepted as integer values for the function and the label gives the purpose of this function.

Types of PHP Annotations

Given below are the types:

1. Built-in Annotations

There are 2 built-in functions in annotations which are as follows:

a. Compiled: This annotation indicates that if the method/function should be JIT compiled or not. It is also a function scope type of annotation.

b. SuppressWarnings: This is another built-in annotation which means that any warnings thrown as part of the execution of the succeeding code below it must be suppressed.

2. Meta Annotations

These are those type of annotations which can be used to apply for other annotations. They are used for configuration of annotations.

a. @Annotations

There is a kind of annotation classes which will contain @annotation.

Code:

[@Annotation]
class MyAnnoExample {
// piece of code
}
Copy after login

b. @Target

As the name suggests, this annotation indicates those types of class elements or a method upon which the annotation will be applicable.

Upon this we can describe one or many targets:

  • Property annotation is just before the property class declaration.
  • Class which is allowed before the declaration of class.
  • Function is declared before the function declaration.
  • Method annotation allows proceeding the method declaration.
  • Annotation is allowed for proceeding to declaration of annotation class.

c. @Repeatable

This annotation means that it may be repeated any number of times when being used.

d. @Inherited

This can also be used on the other user defined annotation classes as a meta-annotation. These inherited annotations are automatically inherited to the respective sub-classes when they are used upon a superclass.

3. Custom Annotations

These are very similar to declarations of the normal class. Each element of the annotation type is defined by each of the property declarations.

Examples of PHP Annotations

Given below are the examples mentioned:

Example #1

Code:

// namespace declaration here
[@Annotation]
[@Target("class")]
class MyAnnoEx {
[@Required]
public string $prop;
public array $arrayProp = [];
public embedAnno $embed;
}
[@Annotation]
// code for embedded annotation goes here
[@Target(["class", "annotation"])]
class embedAnno {
}
[@Annotation]
// example for target annotation
[@Target("property")]
class propAnno {
}
@Annotation
// code for method annotation goes here
@Target("method")
class methodAnno {
public string $val;
public function __construct(string $val) {
$this->val = $val;
}
}
Copy after login

This is just a basic example showing the usage of all the different types of annotations which are shown above. All the ones in the example like embed annotation, property annotation, method annotation are custom annotations.

Example #2

Code:

<!DOCTYPE html>
<html>
<body>
<?php
/**
* @Replace("exmaple", "for", "annotation")
*/
class MyNamedComponent
{
}
echo str_replace("First", "Second", "First Example");
?>
</body>
</html>
Copy after login

Output:

PHP Annotations

In this example we are naming the annotation as replace since the below code represents the usage of string replace function which is str_replace, an inbuilt function of PHP. Using this function, the first parameter passed in the function is replaced by the second one.

Example #3

Code:

<!DOCTYPE html>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<h1>Form Processing using PHP</h1>
<fieldset>
<form id="formex1" method="post" action="formexample.php">
<!--Declaring First name for the form
@Annotation text first_name-->
First_Name:
<input type="text" name="First_Name"/>
<!--@var style color-->
<span style="color:blue;">*</span>
<br>
<br>
<!--Declaring Last_Name for the form
@Annotation text last_name-->
Last_Name:
<input type="text" name="last_name"/>
<span style="color:blue;">*</span>
<br>
<br>
<!--Declaring Location for the form
@Annotation text location-->
Stay location:
<input type="text" name="location"/>
<span style="color:blue;">*</span>
<br>
<br>
<!--Declaring EMAILID for the form
@Annotation text email-->
EmailID:
<input type="email" name="emailID"/>
<span style="color:blue;">*</span>
<br>
<br>
<!--Declaring Password for the form
@Annotation password-->
Password:
<input type="password" name="password"/>
<span style="color:blue;">*</span>
<br>
<br>
<!--Declaring Password for the form
@Radio button password-->
Gender:
<!-- Gender to be selected as either male or female -->
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
<input type="confirm" value="confirm" name="confirm" />
</form>
</fieldset>
<?php
if(example($_POST['confirm']))
{
if(!example($error))
{
echo"<h1>DETAILS RECEIVED</h1><br>";
echo "<table border='2'>";
echo "<thead>";
echo "<th>Argument</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>".$First_Name."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last_Name</td>";
echo "<td>".$last_name."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Stay location</td>";
echo "<td>".$location."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Email Stay location</td>";
echo "<td>" .$emailID."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
}
}
?>
</body>
</html>
Copy after login

Output:

PHP Annotations

In this example, we are showing annotations in combination with the form validation in PHP. Using annotations we are labeling all the parameters which are required as input parameters to the form such as first and last name, email, location and password.

Conclusion

With the above examples we have noticed how annotations are a powerful tool to use and express metadata about our methods, classes or properties. We have also seen how to combine different kinds of annotations to declare workers who will perform certain tasks by writing some metadata about them. This makes them easy to find and gives actual information on whether or not they can be used.

The above is the detailed content of PHP Annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles