PHP의 변수

WBOY
풀어 주다: 2024-08-29 12:34:41
원래의
1243명이 탐색했습니다.

The following article, variables in PHP, provides an outline for the various variables available in PHP. Each variable stores some kind of information where information is a value. This value can be a number, a string, boolean, array, an object, a resource, etc.

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

How to Declare Variables in PHP?

The variables declared store information. Therefore, there are certain things one must know about declaring variables in PHP.

  1. Variables declared always begin with a dollar sign ($). A variable name must begin either with a letter or an underscore but not with a number.
  2. Variables do not contain spaces, and these variable names are a case-sensitive example, $fruit is different from $From.
  3. Variables declaration uses the assignment operator ‘=’ wherein the variable name is on the operator’s left side and the expression on the right side of the operator.
  4. As we know that PHP is a loosely typed language, the variables declared do know in advance what type of variable it will be, meaning that it can be declared as a number, a string, an array, or anything else.
  5. Since the values of the variables are not constant, these values can be converted from one value to another value as and when required.

How to Initialize Variables in PHP?

From the previous, we know that PHP is a loosely typed language and we need not declare the type like whether the variable is of integer, or string or boolean type before using it as it happens in other languages. The type of the variable depends upon the value it stores. Let us learn through examples.

Here in the below example, we see that the height is a float value and the base is an integer value and based on these values, we have calculated the area of the triangle.

Code:

<?php
// example to demonstrate the intialization of variables
$height = 10.5;           //float value
$base = 50;               //integer value
// calculating area of a triangle
$area_of_triangle = ($height * $base) / 2;
// printing area of the triangle
echo 'Area of the triangle is '. $area_of_triangle;
?>
로그인 후 복사

Output:

PHP의 변수

The below code shows all valid and invalid ways of initializing the variables in PHP.

  1. // invalid because of starts with a number
$5input = 'Demo';
로그인 후 복사
  1. // valid because of starts with an underscore
$_input = 'Demo';
로그인 후 복사
  1. // valid
$input = 'Demo';
로그인 후 복사
  1. // valid because it starts with an underscore followed by number and string of characters which is allowed
$_5input = 'Demo';
로그인 후 복사

Types of Variables with Examples

Variables store values. These values assigned to the variables define what type of variable it is. There are eight data types:

PHP의 변수

Let us learn each in detail.

1. Integer

An integer is a whole number. This integer can be positive or negative. (if no significant meaning it is positive) It compulsorily has at least one digit ranging from 0 to 9, with no comma or blanks. It does not have a decimal point. Integers have different notations like

  1. decimal(base 10)
  2. hexadecimal(base 16, prefixed with 0x)
  3. octal(base 8, prefixed with 0)

optionally preceded with a sign either – or +

<?php
//example to demonstrate an integer datatype
$x = 6900;
$y = 45;
//var_dump tells us about the datatype and value of the input number
var_dump($x);
echo '<br>';
var_dump($y);
?>
로그인 후 복사

Output:

PHP의 변수

2. String

A string is a sequence of characters or letters. A string can hold a sequence of numbers, special characters, arithmetic values also. It can be a combination of all, as well. To represent a string, we use single or double-quotes.

<?php
//example to demonstrate string datatype
$input = 'Apple';
echo '<br> $input is my favorite fruit';
echo "<br> $input is my favorite fruit";
?>
로그인 후 복사

Output:

PHP의 변수

3. Boolean

This data type can hold one of two values: true or false, where true is 1, and false is blank.

<?php
//example to demonstrate boolean datatype
$input = true;
// print true
echo "<br> True is ".$input;
$input_value = false;
// print false
echo "<br> False is ".$input_value;
?>
로그인 후 복사

Output:

 PHP의 변수

4. Float

A number with a decimal point or an exponential form is called a floating-point number or type float.

<?php
//example to demonstrate float datatype
$input = 123.45;
$input_value = 9.e5;
var_dump($input);
echo '<br>';
var_dump($input_value);
?>
로그인 후 복사

Output:

PHP의 변수

5. Object

An object is a data type that stores data. Along with data, it also stores information about the processing of the data. An object is declared explicitly by declaring a class. Class is defined with the class keyword. A Class is a structure that contains data members and data methods.

A class is instantiated, and the object is created, and through this object now we can access the members and methods of the class.

<?php
//example to demonstrate object datatype
class Subject{
//defining a string property
public $string = "My favourite subject is Maths";
//defining a method that returns the string property
function display() {
return $this->string;
}
}
//instantiating an object of a class
$object = new Subject;
echo $object->string;
?>
로그인 후 복사

Output:

PHP의 변수

6. Array

It is a collection of similar and dissimilar data types. An array is declared in the form of key-value pair.

<?php
//example to demonstrate array datatype
$directions= array('East','West','North','South');
var_dump($directions);
echo '<br>';
echo $directions[2]
echo '<br>';
echo $directions[0];
?>
로그인 후 복사

Output:

PHP의 변수

7. NULL

When no value is assigned to a variable and the variable is empty, we can use the NULL value.

<?php
//example to demonstrate NULL datatype
$input = 'Demo Test';
var_dump($input);
echo '<br/>';
$input = NULL;
var_dump($input);
?>
로그인 후 복사

Output:

PHP의 변수

8. Resource

A resource a special variable related to an external resource which can be file handling, database connectivity or others

<?php
//example to demonstrate resource datatype
//establishing a connection to database with default values
$connection = mysql_connect("localhost", "root", "");
var_dump($connection);
?>
로그인 후 복사

위 내용은 PHP의 변수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿