


Original text: http://dotnet.dzone.com/articles/php-scripting-language-c
When we plan to create a .net program (including a desktop program or a Web application), it will definitely be quite practical if other languages can be used to extend the functionality of the .net program.
For example, some users can write a simple script to set some settings of this program, or modify how data is persisted in the program, or write a simple plug-in for this .net program. In this article, let’s take a look at how to use PHP as a scripting language for .net programs
Obviously there are many benefits to doing this:
1. Many programmers can write some basic PHP code, and even a junior programmer can write a simple PHP script code for your application
2. PHP is very easy to use. There are already a lot of ready-made PHP code snippets on the Internet that can be copied and used directly
3. Thanks to the Phalanger library (http://phalanger.codeplex.com/), PHP code can easily obtain any .net library and call almost all services provided by .net programs
The scenarios described above are just a small part of the cases where Phalanger from C# (or other programming languages) is used to generate PHP code at runtime. For example, can you imagine a web network architecture using C# to write the domain name module and then using PHP to What does it look like to build a user interface. So this article will show how to run PHP code in a C# program, how to use global variables as parameters to pass to the PHP code, and how to read standard .net streams.
Phalanger is a compiler that compiles PHP scripts into .net bytecode. It is designed to allow seamless bidirectional interoperability between .net and other languages.
This means that you can call .net methods and use .net classes in PHP code (http://wiki.phpcompiler.net/.NET_interoperability), and you can also call PHP methods and use in C# or F# PHP class.(http://wiki.phpcompiler.net/Code_Samples/Standard_mode_interoperability)
At the same time, this article shows another way to use Phalanger: running PHP code through a .net program. Especially when the code to be run is obtained dynamically or cannot be precompiled into an assembly (for example, when the code is later written by the user In this case). When the running PHP code does not have any changes, generally you should use the precompiled script library (http://wiki.phpcompiler.net/Code_Samples/Standard_mode_interoperability), which can achieve higher efficiency because They do not participate in compilation at runtime.
Configuration
I have tested this technology in the ASP.NET 4.0 C# website program. Of course, it is also feasible in .net console programs or desktop applications such as winforms. But remember that your .net program must use .net 4.0 (full profile) as the target .net framework, and must reference at least one Phalanger assembly: "PhpNetCore, Version=2.1.0.0, Culture=neutral, PublicKeyToken= 0A8E8C4C76728C71". Phalanger must be configured correctly in your application. Although it can also be configured manually (http://www.php-compiler.net/blog/2011/installation-free-phalanger-web), the easiest way is to use the installer.
Source code
Incredibly, the core of running PHP code is the method PHP.Core.DynamicCode.Eval, which is in the PhpNetCore.dll assembly. The only troublesome thing may be the large number of parameters required by the method. First we need an available PHP.Core.ScriptContext instance, which is the execution instance of Phalanger to run PHP code. You can get such an instance from the current thread. Please note that PHP is not multi-threaded, so the ScriptContext is only closely associated with one thread
1
var context = PHP.Core.ScriptContext.CurrentContext;
Then we will set the output mode of ScriptContext so that the PHP script can convert the stream we need. Here we will set up two output methods - byte stream and text stream. Note that you must destroy these streams at the end so that all data will be flushed correctly
1
context.OutputStream = output;
2
using (context.Output = new System.IO.StreamWriter(output)) {
We can also set global variables in the ScriptContext, so that we can easily transfer some parameters to the running PHP code.
1
Operators.SetVariable(context, null, "X", "Hello World!");
Ultimately we will use the Eval method to run PHP code. And this method is actually used internally by Phalanger to handle PHP's eval() expression. So that's why this method has so many parameters.
01
// evaluate our code:
02
return DynamicCode.Eval(
03
code,
04
False,/*phalanger internal stuff*/
05
context,
06
null,/*local variables*/
07
null,/*reference to "$this"*/
08
Null,/*current class context*/
09
"Default.aspx.cs",/*file name, used for debug and cache key*/
10
1,1,/*position in the file used for debug and cache key*/
11
-1,/*something internal*/
12
null/*current namespace, used in CLR mode*/
13
);
If the running code behaves the same as the global PHP code, most of the parameters will look nothing special. The most important parameter is code. This parameter is a string containing your php code. Phalanger will first translate and then compile this code. The converted .net bytecode will be stored in memory as a temporary assembly (we also call it a transient assembly)
. Note that the entire translation and compilation process is very fast, because transient assemblies are also cached to speed up running the same PHP code.
As you can see, you can also provide the file name and location of the file in the file name and position parameters; so when you debug the code and step into the expression, it will jump exactly to the position specified by the position parameter.
Note that whether the cached transient assembly is updated will depend on the PHP code previously executed by the ScriptContext (such as defined classes and methods). Only when the PHP code generated twice is consistent, the transient assembly can be cached. This is why the parameters code, file name and position in the Eval method can be cached and reused only when they match the previous ones.
Then we have to remember that you should consider this issue first when running more PHP code snippets later.
Finally, if you plan to use Phalanger in a web application, you should initialize the PHP.Core.RequestContext first, and then destroy it at the end of the php script.
1
using (var request_context = RequestContext.Initialize(
2
ApplicationContext.Default,
3
HttpContext.Current))
4
{ /* all the stuff above */ }
Summary:
That’s all. Because the PHP code executed later also contains defined PHP methods, variables and classes, you can also use them in .net code.
The language of .net application functionality. You can also use this technique to create a web application that uses C# to create the domain name module and PHP to build the user interface.
If you are interested in this and want to get more information, you can check out the latest article on Standard_mode_interoperability (http://wiki.phpcompiler.net/Code_Samples/Standard_mode_interoperability)
Author junwong's blog

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool