Home >Backend Development >PHP Tutorial >Take you to understand the difference between php and C language

Take you to understand the difference between php and C language

烟雨青岚
烟雨青岚forward
2020-07-14 13:12:113581browse

Take you to understand the difference between php and C language

If you have learned C language and now want to learn PHP, the first step is of course to master the basic syntax. The basic syntax of PHP is very similar to that of C, but it also has some unique features. This article introduces the basic syntax of PHP through comparison and in the order of learning C language syntax, hoping to help people who are familiar with C get started quickly.

First of all, let’s clarify an idea. The biggest difference between PHP syntax and C is that PHP emphasizes practicality, while C emphasizes principles. Learning the syntax of C and cultivating rigorous thinking habits are very helpful for understanding the working principle of computers. If a person who has learned C starts to learn PHP, he will feel uncomfortable with PHP's too loose syntax.

The founder of PHP designed PHP to update his own homepage, not to develop an operating system like the founder of C. This is the fundamental reason for the different grammatical styles of the two.

After clarifying this idea, we will introduce the basic syntax of PHP one by one in the order of data types, constants, variables, operators and expressions, flow control, functions, and arrays and compare it with C.

Since this is an introductory course, we only move along the main road. There are many beautiful scenery on the roadside, such as regular expressions. We will explore them later.

PHP’s data types

One significant difference between PHP and C is that neither constants nor variables need to be defined before use (except for variables in classes). PHP automatically determines the data type based on the first assignment.

Think about when we were learning C language, we felt that it was troublesome to define first and then use it (but after "growing up" (I mean after learning C), we all realized its benefits), and we often forgot to define it. , but now that this rule is missing, I feel a little uncomfortable.

PHP’s basic variable types include integer (Integer), floating point (Float), string (String) (this is not available in C, but C has the String class) and Boolean (Boolean) ( C does not, but C does). Constructed types include arrays and objects. In addition, there are two special types: NULL (also available in C) and Resource.

Constant

The way to define constants in PHP is a bit incredible to people who are learning C. It is actually implemented using a define function. PHP functions are really That's awesome. We will see later that defining arrays is also done by functions. We really have to thank PHP for its extremely rich function library, which makes PHP easy to use and powerful.

define function prototype: bool define(string name, value, [, bool case_insensitive])

If the third parameter is TRUE, it means that the constant name is case-insensitive, otherwise it is sensitive, and the default is sensitive. Let’s follow the custom and keep constant names case-sensitive.

Example:

Copy PHP content to the clipboard

PHP code:

 <?php
  define(“C1”,”Hello
 PHP World!”);
  echo C1;
?>

The running result of the above code is the output constant The value of C1 (Hello PHP World!).

By the way, 36aafd3c2422d8273bebb683d205fd9f are the delimiters of PHP code, which distinguish PHP code from HTML code. PHP code statements end with semicolons, which is what we are used to. , In addition, PHP's comment symbols are the same as C. You should know that, but I won't go into details...

This echo is equivalent to C's printf or C's cout, but strictly speaking it is not formatted For output, it is easy to format. You just need to write the HTML code. For example, if you want to break the line after the output, then you can write define("C1","Hello PHP World!0c6dc11e160d3b678d68754cc175188a”);Okay.

Note that PHP also supports '\n' as a newline character, but its meaning is only equivalent to hitting Enter in HTML. In the browser It looks like it’s still on one line.

Variable

In addition to not having to define it, the most unaccustomed thing for C language users is that all variable names must be preceded by a $. You may The designers who will complain about PHP are too money-crazed, but after complaining, you still have to write like this. When writing PHP programs, the usage of the Shift key has increased sharply!

I suddenly discovered an advantage of doing this: constants do not carry $, so the distinction between constants and variables becomes obvious. More importantly, you no longer have to worry about custom variable names conflicting with PHP keywords. You can define a variable called $if, $for, etc. (of course, formally In this case, it is better not to do this, just enjoy it).

The same as C, PHP variable names are case-sensitive, and the naming method follows the naming principles of C identifiers. Remember Do you?

If you know some C and the concept of references, you can skip the following paragraph, just remember that PHP also supports references. Otherwise, take some time to read the following paragraph or go look at C references The concept also works.

Copy PHP content to the clipboard

PHP code:

<?php
$var1=100;
$var2=&$var1;
$var2=200;
echo $var1.”<br>”;
echo $var2;
?>

The result of this code is to output two 200 , are the values ​​of $var1 and $var2 respectively. A newline character is added for clarity when outputting. The period (.) is the connector of strings in PHP.

Why is only 200 assigned to $var2? And $var1 has also become 200. You can also try to change only the value of $var1. You will find that these two variables seem to be tied together.

其实语句$var2=&$var1;中的&符号的含义是将变量名$var2也指向$var1所在的存储空间,也就是说$var2并不是一个新变量,而是$var1的另一个名字,它们对应的是同一段内存空间,不管使用谁都是访问的同一个变量,$var2就叫做对$var1的引用。

引用有什么好处?以后再说。C语言的基本概念(变量名、变量地址、变量值)清楚的话,理解起来应该没有什么困难,如果基本概念不清楚,还是先“温故”再“知新”吧。

顺便说一个有意思的事,如果你在把上面的echo语句写成:

echo“The value of $var1 is”.$var1.”<br>”;

那么你得到的输出将是:

The value of 200 is 200

还记得吗,在初学C语言时你很可能犯过把变量名放在字符串里想输出它的值,结果得到的是变量名,而现在,你的“理想”实现了,而你却又不习惯了,呵呵。

原来PHP在使用双引号作为字符串的定界符时,会自动把变量名替换成相应的值,这样的做法使得我们输出含变量的字符串时变得非常方便,一对双引号下来就可以了。如果你想保持变量名原样输出,那么可以用单引号做字符串的定界符(当然还有其它办法,你可以仔细研究一下PHP的字符串)。

还是要感谢C的严格要求,如果C像PHP这样的话,我们恐怕到现在也搞不清变量名、变量值这些概念。

变量的作用域

PHP的变量作用域与C很类似,在此不准备多说。局部变量在所存在的函数内部有效,全局变量作用域是文件作用域(限于单个PHP文件),若局部变量同全局变量重名,同C的处理方式,全局的被屏蔽。

稍微麻烦一点的是,要想在函数内访问全局变量,需使用global关键字声明,否则的话PHP就认为是一个与全局变量同名的局部变量。

复制PHP内容到剪贴板

PHP代码:

<?php
$a=1;
function func()
{
   echo "The value of a is:".$a;
}
func();
?>

 以上代码没有输出1,为什么呢?PHP把函数里的$a看作是一个全新的局部变量,此$a非彼$a(函数体外的全局变量),此$a未赋值,因此输出为空。

如果我们要想在函数体内部访问全局变量$a的值,须在访问之前声明一句:global $a; 这样PHP就知道要访问的是全局变量$a了。

还有一种方法是利用PHP的系统数组$GLOBALS,该数组是PHP系统自动生成和维护的,它记录了所有全局变量。echo $GLOBALS[“a”];即可输出其中$a的值。

PHP的静态变量仅在局部函数域中存在,同C是完全相同的。

PHP有一种特殊的动态变量,名字听起来很容易让人认为就是C语言的普通变量(动态的、局部的),但这个动态的含义有点特殊,它是指变量名可以动态赋予!也就是说,可以让应用程序的最终用户为变量指定名字!

复制PHP内容到剪贴板

PHP代码:

<?php
$a="newname";
$$a="content";   //newname本是$a的值,但是$$a的含义是以$a的值为名的变量
echo $newname; //$$a等价于$newname
echo $a;
?>

运算符和表达式

PHP在运算符和表达式方面和C极其类似,有算术、逻辑、关系、位运算符及相应的表达式,也有条件运算符(:?)及其表达式,同样还是我们开始提到的那个思想,实用为上,很多限制被取消了,相对较宽松。举个例子:

复制PHP内容到剪贴板

PHP代码:

<?php
$a="1";
$b=1;
if ($a==$b) echo "Equal!";
else echo "Not Euqal!";
?>

按照C的思维方式来看,$a是字符,$b是整型,两者比较是字符的ASCII码值与整数比较,显然不等,而PHP运行结果却是“Equal!”,看到这里,是不是有点冲破封建大家庭的礼教与心上人私奔的感觉?呵呵,抑或是惊呼PHP无法无天?

接下来还有让你目瞪口呆的,若$a="1e3"; $b=1000; 依然是“Equal!”,也就是说PHP在比较时能自动将字符串“按照人的理解方式”进行转换,1e3不就是科学计数法表示的1000吗?甚至$a=”1e3HelloWorld”;都会相等

PHP将字符串转换为数值时会自动截取全部它能理解为数值的部分!

其实C也允许跨越数据类型的比较,比如字符型和整型比较,C也会自动转换类型,但它是“按照计算机的思维方式”转换的,因为字符在计算机里就是按照ASCII码存储的。

PHP的“人性化”也带来了麻烦,当我们想严格比较两个变量的时候怎么办呢?

于是PHP提供了一对特殊的运算符:全等(===)和非全等(!==),只有当值相当且数据类型相同时,才叫全等,两者有一不符,则非全等。

此时,即使1与1.0也是非全等的,原因你一定知道吧。如果你觉得只有这样才踏实,那么恭喜你,你已经被C洗脑了。

运算符有优先级和结合性的概念,这方面和C是类似的,你也许记不清所有的优先级关系,但是没关系,我们有括号呢。

流程控制

PHP的流程控制语句是与C最像的部分了,简直可以照搬。

有两点值得注意,一是switch case语句中case后面可以写任意表达式,而不是C规定的只能是常量表达式,C的这种规定太不近人情了,以至于很多人学完了C还不知道case score〉90:这样的写法错在哪里。现在好了,PHP里面,你可以这样写了。

再就是很奇怪的一点,if elseif else结构中间的else和if可以连在一起写。

此外,PHP还有一个独特的循环结构foreach,是专门为数组遍历准备的,稍后介绍。

函数

PHP用户自定义函数的语法与C也很类似,可想而知,由于PHP弱化数据类型的概念,所以函数的返回值类型也就弱化了,函数定义的一般形式是:

function函数名($参数1,$参数2,……,$参数n)
{
  函数体
  return语句返回值
}

比C的“宽松”之处在于函数可以嵌套定义,但是为了一个明晰的代码结构,还是严格要求自己的好。

这里我们再说说引用。前面提到引用其实就是给变量取个小名(专业的话叫别名),即两个或多个变量名对应同一变量存储空间。

这一概念用在函数参数上特别有用,我们知道实参与形参的结合是单向值传递,即实参将它的值复制给形参,而形参变量在函数体中可能被改变

但由于形参变量会在函数返回时被撤销,所以形参不能将改变了的值传回给实参,这是学C的人都应该十分清楚的,大家都做过那个交换两个数的实验。

这一机制保证了函数只能有一个返回值,当需要返回多个值的时候,我们可以使用引用做形参,这相当于把实参的地址传递给函数,函数对这个地址上的数据进行操作,当然就可以把改变保留下来。

引用的概念是C++里增加的,PHP的函数也支持引用做形参。只要把C++里引用做参数的概念理解清楚了,在PHP里是完全一样的。

PHP有巨大的函数库,比如关于时间的函数就有一大堆,写PHP程序时,当你有个功能想要实现,第一件事应该是查PHP函数手册,看看有没有能满足你的要求的函数,或者是通过多个函数组合实现也行,而不是自己动手去写(练习编程技能或改进PHP者除外),记住一句老话:不要重复发明轮子。

要想掌握PHP,熟练使用常用函数是必须的,但这不是我们这篇文章的目标,有机会专题探索吧。

数组

这回甭指望我说PHP的数组和C差不多了,因为PHP的数组,简直就不是C的数组!PHP的数组应该叫做“集合”,不是紧急集合的集合,是数学意义上的集合,如果你学过数据结构就更明白了。

说白了,PHP的数组就是把一堆数据(什么类型都行)放在一起。这在C里是很疯狂的想法,但是在现实中是很实用的,比如一条数据库记录可能由整型、字符串型、浮点型等不同类型的若干字段组成,

如果能一次读取出来放在一个“数组”中用下标访问,是不是很方便呢?这种“数组”,是不是很像C的结构体呢?其实它比结构体还灵活,它可以自动增减数据元素。

PHP数组的定义是通过array函数实现的,一般形式为:

$数组名=array(键名=>数据,键名=>数据,……, 键名=>数据);

这里的键名在C中叫下标,C规定下标必须是整数且必须从0开始依次递增。

在PHP里,键名非常人性化,对应的数据如果存储的是姓名,键名就可以叫name,是成绩,就可以叫score,当然你如果想用整数也可以,随你的便。如果你懒得在定义数组时指定键名,可以这样写:

$数组名=array(数据1,数据2,……, 数据n);

这时候PHP会按照C语言的方式按数据的先后顺序从0开始自动赋予整型键名。

PHP提供了一个特别方便的显示数组全部元素的函数print_r

复制PHP内容到剪贴板

PHP代码:
 
<?php
$arr1=array(100,200,300,400);
$arr2=array("num"=>100,"name"=>"Liuxy","score"=>98);
print_r($arr1);
echo "<br>";
print_r($arr2);
?>

以上代码的输出结果如下:

Array ( [0] => 100 [1] => 200 [2] => 300 [3] => 400 )
Array ( [num] => 100 [name] => Liuxy [score] => 98 )

若要定义二维数组,可以嵌套地使用array函数,同C类似,也是把二维数组的每一行看作是一个一维数组,构成每一行的一维数组可以互不相同。如:

复制PHP内容到剪贴板

PHP代码:

$arr=array(
           "row1"=>array(100,200,300,400),
           "row2"=>array("num"=>100,"name"=>"Liuxy","score"=>98)
         );

PHP数组元素的访问同C类似,都是数组名[键名]的形式。

PHP数组的遍历可以通过foreach语句实现,foreach语句格式如下:

foreach (数组名as  变量名)数据元素处理语句;

翻译成C语言就是:

for(i=0;i<n; i++){变量名=a;其他包含“变量名”的处理语句}
foreach等价于前面的for (i=0;i<n; i++)

as等价于“变量名”与a之间的等号,这下你明白了吧。

例如:

复制PHP内容到剪贴板

PHP代码:

<?php
$arr=array(1,2,3,4,5,6);
foreach ($arr as $value ) echo”$value<br>”;
?>

输出结果是什么?想想看。

如果还想把对应的键名也同时输出出来,可以用这样的形式:

foreach ($arr as $key=>$value) echo“键名为$key的元素值为$value”;

在C中遍历二维数组我们一般用二重for循环,相应地,PHP中的foreach也可以嵌套使用,分析一下下面的程序你就明白了:

复制PHP内容到剪贴板

PHP代码:

<?php
$arr=array(
             "row1"=>array(100,200,300,400),
             "row2"=>array("num"=>100,"name"=>"Liuxy","score"=>98)
           );
 
foreach ($arr as $key=>$value)
{
    echo "$key=>$value";
    echo "<br>";
    foreach ($value as $k=>$var) echo "$k=>$var<br>";
}
?>

PHP的数组元素是可以动态增长的,这是C里面不敢想的。

为数组增加一个元素很简单,同访问数组元素一样,只不过键名是新的或者为空,如$arr[new]=3; 或$arr[]=3,这样做的结果是PHP为数组$arr增加一个键名为new的元素其值为3,若键名为空,则以当前整型键名的最大值加1作为默认的键名分配给新的元素。

PHP的这种动态增长数组有时候很方便,但也带来隐患,比如当我们企图修改已存在的元素值而写错了键名时,就变成了新增一个元素,而这样的逻辑错误,系统是不会报错的。

可以增长就可以缩减,要想删除一个数组元素,可以使用unset函数,如删除上面新增的那个元素,可以写成unset($arr[new])。也可以使用unset函数删除整个数组结构,如unset($arr),要注意这同逐个删除全部数组元素不同,后者还保留有数组的结构。

形象地说,后者是人去楼空,但楼还在,前者连楼也拆除了。有意思的是删除数组全部元素后如果新增一个元素,它的默认键名将延续之前数组的最大键名递增,要想从0开始,可以使用array_values函数重置,如$arr=array_values($arr)。

提醒大家的是,PHP为数组的排序、查找、合并、拆分提供了大量函数,用到这些基本算法时,不用再去翻数据结构课本了,呵呵……

这个专题主要把精力集中在PHP的基本语法上,通过与C的对比来加深理解,有很多细节问题未深入讨论。学习任何东西都是一个螺旋上升的过程,我们先浏览一下知识脉络,更多的需要在实践中去体会。

下一个专题我们是不是研究一下PHP5的面向对象?你可能会说“我没学过C++”,没关系,这回我们不比较了,C++的面向对象概念是所有语言中最复杂的,而PHP5的面向对象由于是从实用出发所以比较简明,你不妨先学PHP5的面向对象,理解面向对象的概念,然后再去啃C++的OOP吧。

感谢大家的阅读,希望大家收益多多。

本文转自: https://blog.csdn.net/ailxxiaoli/article/details/52199337

推荐教程:《php教程

The above is the detailed content of Take you to understand the difference between php and C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete