|
創(chuàng)建你自己的Java類非常容易。新建一個(gè)phptest.Java文件,將它放置在你的Java.class.path目錄下,文件內(nèi)容如下:
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));
}
}
}
}
創(chuàng)建這個(gè)文件后,我們要編譯好這個(gè)文件,在DOS命令行使用Javac phptest.Java這個(gè)命令。
為了使用php測(cè)試這個(gè)Java類,我們創(chuàng)建一個(gè)phptest.php文件,內(nèi)容如下:
<?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是一種強(qiáng)制類型語(yǔ)言,而php不是,這樣我們?cè)趯⑺鼈內(nèi)诤蠒r(shí),容易導(dǎo)致錯(cuò)誤,于是我們?cè)谙?a href=/itjie/Javajishu/ target=_blank class=infotextkey>Java傳遞變量時(shí),要正確指定好變量的類型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";
這只是一個(gè)很小的例子,你可以創(chuàng)建你自己的Java類,并使用php很好的調(diào)用它!
php技術(shù):php&amp;java(二),轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。