Example #1
0
        static void Main()
        {
            // sideload assembly containing compiled PHP code:
            Context.AddScriptReference(Assembly.Load(new AssemblyName("phplib")));

            // create host for PHP code (Runtime Context):
            using (var ctx = Context.CreateConsole())
            {
                // declare global function in PHP runtime context
                ctx.DeclareFunction(RoutineInfo.CreateUserRoutine("is_valid_url",
                                                                  new Func <string, bool>((url) => {
                    return(new Uri(url).IsAbsoluteUri);
                })));

                // call the global code from "class-user.php" which declares class
                ctx.Include("", "inc/class-user.php");

                //
                dynamic u1 = ctx.Create("User", "Jacob", "https://example.org", "*****@*****.**");
                u1.Authenticate();

                var u2 = new DotNetUser(ctx, "Jacob", "https://example.org", "*****@*****.**");
                u2.Authenticate();
            }
        }
Example #2
0
        static void Main()
        {
            // acquire PHP Context
            // Context is a single-threaded object manntaining state of PHP program.
            // There are several ways of getting/creating the object, see https://docs.peachpie.io/api/ref/context/ for details
            // ContextExtensions.CurrentContext can be overriden, by default it creates a new context per thread without
            var ctx = ContextExtensions.CurrentContext;

            // declare global function in Context
            ctx.DeclareFunction("is_valid_url", new Func <string, bool>((url) =>
            {
                return(new Uri(url).IsAbsoluteUri);
            }));

            // invoke the script "class-user.php"
            // The script declares class User in Context
            ctx.Include("", "class-user.php");

            // invoke the script "functions.php"
            // require_once semantic
            // the script declares function is_valid_email() in Context
            ctx.Include("", "functions.php", once: true, throwOnError: true);

            // call function is_valid_email(...)
            // global functions have to be declared and called using Context.Call():
            Debug.Assert(ctx.Call("is_valid_email", "*****@*****.**"));

            // classes can be used as they are:
            var u1 = new User("Everyone", "https://www.example.org/", "*****@*****.**");

            u1.Authenticate();

            // classes can also be created dynamically:
            dynamic u2 = ctx.Create("User", "Jacob", "https://example.org", "*****@*****.**");

            u2.Authenticate();

            var u3 = new DotNetUser("Jacob", "https://example.org", "*****@*****.**");

            u3.Authenticate();
        }