CS174
Chris Pollett
Mar 13, 2017
class MyClass { public $field_var1; public $field_var2 = 5; ... const constant1; const constant2; ... function __construct($arg1, $arg2) { //constructor code } function myFun1() { // code } ... }
new operator
. To dereference fields, or invoke instance functions we use the arrow -> operator.
$arg1 =5; $arg2 = 6; $my_class = new MyClass($arg1, $arg2); echo $my_class->field_var1; $my_class->myFun1();
require("MyClass.php"); //or more likely require_once("MyClass.php");
public $my_variable = 0;
function __construct($n=0) { $this->my_variable = $n; }
private $my_field; protected function myMethod() { /* some code*/}
var $my_field;This is less clear than the public syntax so should be avoided.
class Foo{ static $bob=1;} echo "bob: ".Foo::$bob;
class Goo{ const blob=1;}
Goo::blob
define("PI", 22/7); echo PI;
Which of the following statements is true?
$my_copy = clone $my_obj;
class A{} class B extends A {}
interface MyInterface { function method1($a, $b); }
class C implements MyInterfaceA, MyInterfaceB {}
class A {function foo(){} } class B extends A {function foo(){} }
class A {final function foo() {} /* can't override*/ }
namespace TheNameOfMyNamespace; // code for namespace class A { //code for class A } function foo() { }This declaration with the same name can be at the top of multiple files if you would like to group the contents of these files into the same namespace.
namespace TheNameOfMyNamespace\MySubNameSpace; //code
namespace D { // code for D } namespace E { // code for E }
namespace N; function foo() { //some code } foo(); //assume N namespace.
M\foo(); /*in context of above we are in N namespace already, so M\foo() means the foo() in N\M namespace. */ \N\M\foo(); \time(); //time function in the global (default) namespace.
use A\B\C; //rather that type $a= new A\B\C(); you can type $a= new C(); use D\E\F as G; //rather than typing D\E\F\goo(); could type G\goo();
namespace seekquarry\yioop;
namespace seekquarry\yioop\models;
if (file_exists(__DIR__."/../../vendor/autoload.php")) { require_once __DIR__."/../../vendor/autoload.php"; } else { spl_autoload_register(function ($class) { // project-specific namespace prefix $prefix = 'seekquarry\\yioop\\tests'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { $prefix = 'seekquarry\\yioop'; $len = strlen($prefix); // no, move to the next registered autoloader if (strncmp($prefix, $class, $len) !== 0) { return; } else { $check_dirs = [WORK_DIRECTORY . "/app", BASE_DIR]; } } else { $check_dirs = [PARENT_DIR . "/tests"]; } // get the relative class name $relative_class = substr($class, $len); // use forward-slashes, add ./php $unixify_class_name = "/".str_replace('\\', '/', $relative_class) . '.php'; foreach($check_dirs as $dir) { $file = $dir . $unixify_class_name; if (file_exists($file)) { require $file; break; } } }); }