簡介:這是php 與 java(二)的詳細頁面,介紹了和php,有關的知識、技巧、經驗,和一些php源碼等。
class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=324409' scrolling='no'>
例子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很好的調用它!
作者:井中月
轉載:http://www.chinalinuxpub.com/read.htm?id=299
“php 與 java(二)”的更多相關文章 》
愛J2EE關注Java邁克爾傑克遜視頻站JSON線上工具
http://biancheng.dnbcw.info/php/324409.html pageNo:15