• 技术文章 >php教程 >php手册

    php与java(二)

    2016-06-13 10:14:02原创567
    作者:井中月

    例子1:创建和使用你自己的JAVA类
    创建你自己的JAVA类非常容易。新建一个phptest.java文件,将它放置在你的java.class.path目录下,文件内容如下:
    public class phptest{
    /**
    * A sample of a class that can work with PHP
    * NB: The whole class must be public to work,
    * and of course the methods you wish to call
    * directly.
    *
    * Also note that from PHP the main method
    * will not be called
    */
    public String foo;
    /**
    * Takes a string and returns the result
    * or a msg saying your string was empty
    */
    public String test(String str) {
    if(str.equals("")) {
    str = "Your string was empty. ";
    }
    return str;
    }
    /**
    * whatisfoo() simply returns the value of the variable foo.
    */
    public String whatisfoo() {
    return "foo is " + foo;
    }
    /**
    * This is called if phptest is run from the command line with
    * something like
    * java phptest
    * or
    * java phptest hello there
    */
    public static void main(String args[]) {
    phptest p = new phptest();
    if(args.length == 0) {
    String arg = "";
    System.out.println(p.test(arg));
    }else{
    for (int i=0; i < args.length; i++) {
    String arg = args[i];
    System.out.println(p.test(arg));
    }
    }
    }
    }
    创建这个文件后,我们要编译好这个文件,在DOS命令行使用javac phptest.java这个命令。
    为了使用PHP测试这个JAVA类,我们创建一个phptest.php文件,内容如下:
    $myj = new Java("phptest");
    echo "Test Results are " . $myj->test("Hello World") . "";
    $myj->foo = "A String Value";
    echo "You have set foo to " . $myj->foo . "
    n";
    echo "My java method reports: " . $myj->whatisfoo() . "
    n";
    ?>
    如果你得到这样的警告信息:java.lang.ClassNotFoundException error ,这就意味着你的phptest.class文件不在你的java.class.path目录下。
    注意的是JAVA是一种强制类型语言,而PHP不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";
    这只是一个很小的例子,你可以创建你自己的JAVA类,并使用PHP很好的调用它!

    php入门到就业线上直播课:查看学习

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    自己动手写 PHP MVC 框架:点击学习

    快速了解MVC架构、了解框架底层运行原理

    上一篇:取出任意日期内的所有日期,可以区分大小月 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• mysql 数据备份类代码• Xgcalendar 新增Php demo• PHP 采集程序原理分析篇• PHP类中的魔术方法(Magic Method)简明总结,magicmethod• PHP 教程之如何使用BLOB存取图片信息实例
    1/1

    PHP中文网