PHP and C # mixed programming like rose,
The background of the story is that there is a set of projects, and the server side is written in C #. To accomplish something, it needs to use a component, which is small but important, unfortunately, this component is written in PHP, if a PHP environment is set up to use this component, it seems a bit high-risk (and there are other unforeseen obstacles ). Some readers may make a "protest": Isn't it written in PHP? simply look at the source code and translate a C # version. Isn't that enough? However, the fact is not as beautiful as imagined. In short, it is impossible to do so.
Today, C # is very powerful. In addition to common website development, desktop development, and Native Windows Phone and App Store Development, you can also perform other development such as IOS and Android, or use CLR to hold up a JVM (IKVM here. NET) to run Java applications. Of course, you can also compile PHP into IL to run PHP website programs.
In this article, we will discuss how to implement PHP and C # mixed programming as follows:
(1) PHP and C # glue: "Phalanger"
(2) test run PHP
(3) how to add a PHP class library
(4) Mixed interaction between C # and PHP
(5) be cautious when picking beautiful roses.
Click here to download the sample code in this article.
1. What is Phalanger?
Phalanger can compile PHP into a DLL for C # Calls.
Phalanger official website is: http://www.php-compiler.net/
To do mixed programming, first download an installation package from the official website.
After downloading the package, open the package and double-click Setup to start installation.
Install these files. The first two files must be installed, and the last one is the template file. If you do not want to install them, the template file will contain "Already installed ". As shown in the figure, we can know that it only supports Framework 4.0.
After installing the above, we need the "glue.
2. Run a php program in. NET.
Well, phpinfo (), I didn't guess. This function should be the first one for all readers. It is also a function that must be written after the PHP environment is set up. Let's try this function.
First, create an empty WebApplication.
Then add a php file. Because we didn't directly add a php file, we randomly added a file with a smaller content, and changed its suffix to php and deleted the code in it.
Write our code (with Smart Tips, advanced !!!) :
Then press F5"
Then the page we wanted was displayed miraculously.
3. Add a PHP class library
In fact, even if we write native PHP, we need to use a large number of PHP libraries, such as MySQL, GD, and CURL. Here, of course, we also need to use those libraries. However, here, the libraries we use are not those in PHP/ext, but the libraries that Phalanger has prepared for us. They are installed on our computers along with the installation of Phalanger, if you are interested, you can open the GAC Directory, which contains many php headers, which are the libraries related to Phalanger.
If you need to use any library, add it to the phpNet node of WebConfig. For example, if you need to use the MySQL library, configure it in WebConfig.
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Access the http://go.microsoft.com/fwlink/ for detailed messages about how to configure ASP. NET applications? LinkId = 169433 --> <configuration> <system. web> <compilation debug = "true" targetFramework = "4.0"/> </system. web> <phpNet> <classLibrary> <add assembly = "PhpNetMySql, Version = 3.0.0.0, Culture = neutral, publicKeyToken = 2771987119c16a03 "section =" mysql "/> </classLibrary> </phpNet> </configuration>Web. Config
Note that the MYSQL extension library should be on CodePlex, rather than the built-in, the built-in version of the link to the high-board MYSQL may encounter problems (Address: http://phalangermysql.codeplex.com/releases/view/103022)
Note that the extension on CodePlex is downloaded.
The MySql library name is incorrect. The correct one is "MySql. Data. dll". Please pay attention to it.
Then write down the code for reading the database information:
<? Php/***** determine whether the database is loaded *****/$ extensionName = "mysql"; if (! Extension_loaded ($ extensionName) {echo $ extensionName. 'Not loaded in'; exit;}/***** operate mysql *****/$ host = "192.168.70.128"; $ name = "root "; $ pwd = "root"; $ conn = mysql_connect ($ host, $ name, $ pwd) or die ("mysql database connection failed"); mysql_select_db ("phalangerdb ", $ conn) or die ("unable to select database"); mysql_query ("set names utf8"); $ sqlstr = "select * from person "; $ result = mysql_query ($ sqlstr); echo '<pre>'; while ($ row = mysql_fetch_row ($ result) {print_r ($ row );} echo '</pre>'; mysql_free_result ($ result); mysql_close ($ conn );Mysqlextension. php
Then run and view the result:
It successfully reads the data from our database and outputs the data to the page.
4. Interaction between C # and PHP
Since it is mixed programming, if there is no mutual call between the two languages, how can it be called mixed programming? In this section, we have two main parts: one is to call the C # function in PHP, and the other is to drop the PHP function in C.
PHP calls C #. This is the main example on the Phalanger official website. We will not explain it here. Readers who need it can move to the Phalanger official website to view the Blog. This article explains how to call PHP functions in C #, which has a higher usage probability and lacks relevant information on the official website.
First, create a PHP function:
<? Phpfunction Sum ($ a, $ B) {return $ a + $ B;} function SayHello () {return 'Hello, I am xiaodie Jing hong ';}Fun. php
Create a WebForm page program and call it in CodeBehind (here is a simple addition example ):
Namespace PhalangerDemo. demo3 {using System; public partial class WebForm1: System. web. UI. page {private PHP. core. scriptContext phpContext; public WebForm1 () {phpContext = PHP. core. scriptContext. currentContext; phpContext. include ("Fun. php ", true);} protected void Page_Load (object sender, EventArgs e) {var context = phpContext. call ("SayHello", new object [] {}). toString (); Response. write (context . StartsWith ("&")? Context. substring (1): context);} protected void btnAdd_Click (object sender, EventArgs e) {var num1 = txtNum1.Text as object; var num2 = txtNum2.Text as object; var result = phpContext. call ("Sum", new object [] {num1, num2 }). toString (); txtRes. text = result. startsWith ("&")? Result. Substring (1): result ;}}}View Code
Then run the command in the page to see, Cool:
Here, I want to explain the code of CodeBehind (C #). Its principles are as follows:
(1) obtain the PHP context object PHPContext first.
(2), and then to the PHPContext require_once we write "Fun. php"
(3) Use the Call method. The first parameter is used to pass in the method name, and the second parameter is used to pass in parameters of the Object array type. Call functions in PHP
(4) After the called PHP function is executed, it is returned. And filter the "&" characters at the beginning.
For more in-depth research, such as how to create a New PHP Class, I did not conduct any in-depth research, so I will not describe it here. Interested readers can study it on their own, you are also welcome to share this experience.
5. This beautiful and ugly Phalanger
In the previous chapters, Phalanger is so beautiful and outstanding. It looks like a rose. It looks so bright and smells so fragrant, but when you want to pick it, it is indeed the thorns in your hands. Only when you cut the wound and shed blood can you feel the pain of picking this rose.
After I finish the story at the beginning, the readers can probably guess what the situation is. That's right, my attempt failed, this PHP component cannot run normally.
Below, I will share with you the fatal scars on these two components:
(1) if, the true and false recognition of byte is inconsistent.
Read an object and use if (byte []) to check whether the object is empty, in native PHP, true/false can be determined based on whether the input byte [] is null, while Phalanger always returns false.
(2) The execution results of the same PHP built-in functions are inconsistent.
The inconsistent running effects of the functions mentioned here do not mean that the effects are completely inconsistent. Normal use is still normal (as I have read mysql just now ), however, a very small number of functions run under special conditions and the results are different in native PHP and Phalanger.
Of course, there are one hundred hairt and one hundred million readers, each of whom has their own love for radish and vegetables. Phalanger is worth the trouble in the end. How should we use it? It's up to all the readers to play it on their own.
Where is php simpler than C?
Why is php simpler than c?
1. It doesn't mean how simple the syntax is. In fact, the c syntax is not complex.
2. c is relatively underlying, and many things must be implemented by yourself, such as dynamic arrays, sorting, searching, dictionaries, strings, memory ,...... Many things cannot be achieved if they do not have certain algorithm skills or have a certain understanding of computer principles. php is a relatively high-level language and has many things, for example, all the systems mentioned above have already been done for you. For example, if you simply search for a string in a string and write it in c, you may need a large piece of code, php is a function that can be used directly without considering resource release.
3. php comes with some rich libraries. Most problems in development can be easily solved, and c is not that easy.
Therefore, php is simpler than c
Which of the following languages can be used to learn php and C? Several Questions
If you have a C language foundation, PHP is very simple. If you do not have it, you are advised to directly learn PHP, which is not very difficult.
Generally, C is learned first, and PHP is learned again, but there are similar features between languages. It is certainly helpful to learn other languages.
PHP code writing ~ In three months, you can create some web page background programs. C has more content than PHP, and it is difficult. It is difficult to be proficient without half a year.
For your major, it is recommended to study C instead of PHP. It is okay to study Single-Chip Microcomputer Development carefully for three months.
The intermediate PHP language does not rely on reading books, but on accumulation of work. It is generally used as a PHP programmer ~ Two years can reach the intermediate level