PHP & JAVA (2)

zhaozj2021-02-08  498

Example 1: Creating and use your owen classescreating your owne. Open a new text file called phptest.java. Make Sure IT IS in Your

Java.class.path, as specified in your php.ini file. In That File, Enter the Following:

Public class pHPTEST {

/ **

* A Sample of a class this 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 caled 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

String arg = args [i];

System.out.println (p.test (arg));

}

}

}

}

Once you have created the file, you want to compile it with javac phptest.java at the command line. This will depend on having the java / bin directory in your PATH environment variable. Once compiled, you can test the class on the command line . Try java phptest, or java phptest hello world. This class is made accessible on the command line, via the main () method. This is not required for our Java PHP explorations, but is a nice way to see the class at Work.to test this new class with php, Create a new php file on your web server caled phptest.php. It Should Contain The Following:

". $ 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";?>

If you get a warning: java.lans your pHPTEST.CLASS.PATH SPECified in Your php.class.path specified in your php.class.path specified in your php.ini file.

One thing to remember is that Java is strongly typed, and PHP is not This could cause problems when Java expects a String, but receives an Integer (or visa-versa) Try replacing the line:.. $ Myj-> foo = " A string value "; with $ myj-> foo = 12345678; and see what happens.

You Should Cast Your Variables To The Correct Type Before Passing The Correct Type Before Passing The Correct Type Before Passing The Correct Type, Eg: $ Myj-> Foo = (String) 12345678; Or $ myj-> foo = "12345678";

转载请注明原文地址:https://www.9cbs.com/read-502.html

New Post(0)