欢迎光临
我们一直在努力

php&java(二)-PHP教程,PHP应用

建站超值云服务器,限时71元/月

例子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文件,内容如下:

<?php

$myj = new java("phptest");

echo "test results are <b>" . $myj->test("hello world") . "</b>";

$myj->foo = "a string value";

echo "you have set foo to <b>" . $myj->foo . "</b><br>n";

echo "my java method reports: <b>" . $myj->whatisfoo() . "</b><br>n";

?>

如果你得到这样的警告信息:java.lang.classnotfoundexception error ,这就意味着你的phptest.class文件不在你的java.class.path目录下。

注意的是java是一种强制类型语言,而php不是,这样我们在将它们融合时,容易导致错误,于是我们在向java传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";

这只是一个很小的例子,你可以创建你自己的java类,并使用php很好的调用它!

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » php&java(二)-PHP教程,PHP应用
分享到: 更多 (0)

相关推荐

  • 暂无文章