such as Rose-like PHP and C # mixed programming

Source: Internet
Author: User
Tags php language php class php website php write

The background of the story is this, a set of projects, the server is written in C #, in order to accomplish something, it needs to use a component, this component is very small but very important, unfortunately, this component is written in PHP language, If you build a PHP environment specifically to use this component, it looks like a bit of flak (and other unforeseen resistance). Perhaps some readers will come up with a "protest": not PHP write, directly read the source code translated a copy of the C # version of the line? But the truth is not as good as imagined, in short it is not possible to do so in the near future.

Today's C # is very powerful, it can do our common site development, desktop development and native Windows Phone, App Store development, but also can do other such as iOS, Android development , but also by using the CLR to hold up a JVM (here, ikvm.net) to run Java applications, of course, you can also compile php into IL to run the PHP website program.

In this article, we discuss how to do mixed PHP and C # programming as follows:

(1), PHP and C # glue: "Phalanger"

(2), Kind run PHP

(3), how to add PHP class library

(4), C # and PHP mixed intermodulation

(5), beautiful as roses, picking must be cautious

For the sample code in this article, please click here to download.

1. What is Phalanger

What is Phalanger, the simplest generalization is that it can compile PHP into DLLs for our C # call.

Phalanger's official website is: http://www.php-compiler.net/

To do mixed programming, we first have to download an installation package from the official website.

After downloading, open the package and double-click Setup to start the installation.

These are installed, the front two must be installed, the last is a template file, do not want to install it, it will be installed if it would write "already installed". From the diagram, we can get a message that it only supports the Framework 4.0.

After installing the above things, we need the glue to get it.

2. Run a PHP in. net

Well, phpinfo (), I'm not guessing, this function should be the first to be knocked out by the readers, and a function that must be written after the PHP environment is built. We also kind, try to execute this function.

Let's start by creating an empty WebApplication

Then add a php file, because we do not have a direct PHP file to add, so we have to add a little bit less content of the file, and then change its suffix to PHP and delete the light inside the code.

Write our code (also with smart tips, advanced!!!) ):

Then press "F5"

And then miraculously appeared the page we wanted.

3. Add PHP class Library

In fact, even if we are writing native PHP, we need to use a lot of PHP libraries, such as MySQL library, GD library, Curl Library and so on. Of course there are no exceptions, and we also need to use those libraries. But here, we use the library is not the Php/ext in the library, but Phalanger to prepare the library, they with the installation of Phalanger installed in our computer, interested readers can open the GAC directory, there will be a lot of Php start folder , those are the libraries associated with Phalanger.

Which library do you need to use to add your own under the Phpnet node of webconfig, such as I need to use MySQL library, then in Webconfig this configuration

<?XML version= "1.0" encoding= "Utf-8"?><!--For more information about how to configure an ASP. NET application, visit the http://go.microsoft.com/fwlink/?LinkId=169433 -<Configuration>    <system.web>        <compilationDebug= "true"targetframework= "4.0" />    </system.web>  <phpnet>    <classlibrary>      <AddAssembly= "Phpnetmysql, version=3.0.0.0, Culture=neutral, publickeytoken=2771987119c16a03" Section= "MySQL"/>    </classlibrary>  </phpnet></Configuration>
Web. config

Note here that MySQL's extension library should use CodePlex, rather than the self-brought version of the link High Board MySQL may encounter problems (address as follows: http://phalangermysql.codeplex.com/releases/view/103022)

There is another point to note that this is the case when the extensions on the CodePlex are downloaded.

MYSQL Library naming problems, the correct should be "MySql.Data.dll", please pay attention to readers.

Then write down the code we read about the database:

<?PHP/** * * * Determine if the library is loaded * * **/ $extensionName= "MySQL";if(!extension_loaded($extensionName)){    Echo $extensionName.‘ Not being loaded in '; Exit;}/** * * Operation 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 results:

It succeeds in reading something from our database and outputting it to the page.

4, C # and PHP intermodulation

Since it is mixed programming, how can it be called mixed programming if there is no mutual invocation between the two languages? In this section, we are mainly divided into two parts, one is the PHP C # function, and the other is C # off PHP functions.

PHP Call C#,phalanger Official website of the main examples are this, here is not to explain, the need for readers can go to the Phalanger website to see the blog. This article explains the use of higher probability and is also the official website of the lack of information in C # call PHP function.

Let's start by creating a PHP function:

<? PHP function Sum ($a,$b) {    return$a+$b;} function SayHello () {    return ' Hello, I'm little butterfly Jinghong ';}
fun.php

Then create a new WebForm page program and call it in codebehind (here is a simple addition example):

namespacephalangerdemo.demo3{usingSystem;  Public Partial classWebForm1:System.Web.UI.Page {PrivatePHP.        Core.scriptcontext Phpcontext;  PublicWebForm1 () {Phpcontext=PHP.            Core.ScriptContext.CurrentContext; Phpcontext.include ("fun.php",true); }        protected voidPage_Load (Objectsender, EventArgs e) {            varContext = Phpcontext.call ("SayHello",New Object[] { }).            ToString (); Response.Write (context. StartsWith ("&") ? Context. Substring (1): Context); }        protected voidbtnAdd_Click (Objectsender, EventArgs e) {            varNUM1 = Txtnum1.text as Object; varnum2 = Txtnum2.text as Object; varresult = Phpcontext.call ("Sum",New Object[] {num1, num2}).            ToString (); Txtres.text= result. StartsWith ("&") ? Result. Substring (1): result; }    }}
View Code

And then run the page to see, Cool:

Here, I want to explain the codebehind (C #) part of the code, which is probably the following principle:

(1), first get the context object of PHP Phpcontext

(2), and then go to phpcontext require_once we wrote "fun.php"

(3), through the call method, the first parameter passed in the method name, the second parameter passed into the object array type parameter. Invoking a function in PHP

(4), after the invocation of the PHP function is completed, its return is received back. and filter the "&" character at the beginning.

As for the more in-depth, such as how to new a PHP class, I did not conduct in-depth research, so here is not described, interested readers can do their own research, but also welcome the experience of readers to share.

5. This beautiful and ugly phalanger

In the previous chapters, Phalanger's performance is so beautiful and excellent, it is like a rose, it looks so bright, smell is so delicate fragrance, but when you want to pick it, holding it is indeed a rose under the thorn. It is only when you cut through the wound bleeding, you feel the original picking this rose is so painful.

I continue to finish the story at the beginning, at this point, the reader can probably also guess what is the situation, yes, my attempt failed, this PHP component does not work properly.

Below, I would like to share with you two of the fatal scars this component has encountered:

(1), if the true and false recognition of byte is inconsistent.

The same is to read a file, through if (byte[]) to determine whether the file is empty, the native PHP can be based on the incoming byte[] is null to determine whether the true/false, and Phalanger always return false anyway.

(2), the same PHP built-in functions, the effect of execution is inconsistent.

The functions described here are inconsistent not to say that the effect is completely inconsistent, the normal use is not a problem (as I just read MySQL), but a very few of the functions under special conditions to run the results in the original PHP and Phalanger is not the same.

Of course, 100 readers have 100 Heimlet, radish green vegetables each their own, Phalanger is not worth to use, how should use, or all by the readers themselves game.

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.