創建你自己的JAVA類非常容易。新建一個phptest.java文件,將它放置在你的java.class.path目錄下,文件內容如下:

public class phptest{
/**
* A sample of a class that can work wit " /> 日韩精品99,亚洲最大成人,亚洲最大成人

色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

php&java(二)

例子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很好的調用它!

php技術php&amp;amp;java(二),轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 甘洛县| 青河县| 汽车| 齐河县| 株洲市| 会同县| 项城市| 闵行区| 泾源县| 奉贤区| 安西县| 托里县| 方正县| 郁南县| 黄骅市| 确山县| 台江县| 无棣县| 英德市| 廉江市| 利辛县| 金阳县| 芜湖市| 阿尔山市| 花垣县| 故城县| 兰州市| 上蔡县| 新津县| 贞丰县| 黄梅县| 黄浦区| 田林县| 永寿县| 盱眙县| 化州市| 册亨县| 慈利县| 家居| 临夏市| 施甸县|