I have coded my own PHP auto class loader but I receive the following error when I try to use the class functions with the class
Fatal error: Call to a member function Test() on a non-object
I would also like to know if this approach is the best approach available and if anyone suggests a better way of coding this then I will appreciate it.
$class = array();
foreach (scandir(include_dir) as $filename)
{
if (is_file(include_dir . '/' . $filename))
{
//its a php file, lets do this!
if (substr($filename, -4) == '.php')
{
$page = preg_replace('/\.php$/','',$filename);
$class[$page] = GetClass($page);
}
}
}
$class['Blue']->Test2();
$class['Blue2']->Test();
Iat seems that this error only occurs when there is numbers in the filename / class
And here is class loader file that i include in my index the class Blue works but Blue2 doesn't and throws that error.
function GetClass($class)
{
if (CheckAllOkay($class))
{
include('/blue/' . $class . '.php');
if (ClassCanBeAutoLoaded($class))
{
$newclass = new $class;
return $newclass;
}
}
}
function ClassCanBeAutoLoaded($class)
{
return class_exists($class);
}
function CheckAllOkay($class)
{
return file_exists($class);
}
Here is the class Blue2
<?php
class Blue2
{
function __construct()
{
echo '[LOADED]';
}
public function Test()
{
echo '[TEST CALLED]';
}
}
?>
Class Blue is the same is just echos a diffrent text and has a diffrent class name
Related
i saw a lot of ways that you can use to call a class inside another one in PHP and i want your opinion about the shortest version of calling a class.
lets say we have a class name view,
and another class name controller
class View
{
private $data = array();
private $render = FALSE;
public function __construct($template , $datas = null)
{
try {
$file = strtolower($template) . '.php';
if (file_exists($file)) {
if($datas > 0) {
foreach($datas as $data) {
array_push($this->data, $data);
}
}
$this->render = $file;
} else {
die('Template ' . $template . ' not found!');
}
}
catch (customException $e) {
echo $e->errorMessage();
}
}
public function __destruct()
{
extract($this->data);
include($this->render);
}
}
and
require_once "system/autoload.php";
class Controller {
function index() {
$view = new View('something');
}
i know that i can use
$view = new View('something');
or use OOP and extent and call a function from view inside controller like
$this->viewFunction();
but is there any way that i can call view class inside controller like this
View('something)
i want to make it shortest version possible
if it is not possible or i have to make change inside compiler well just give me the shortest version
thank you all
You can surely do this in PHP. Have a look at magic methods, especially __invoke()
class View
{
public function __invoke(string $template)
{
return $template;
}
}
You can simply invoke it by doing
$view = new View();
$view('my template');
I have Apache running on port 81. My project folder is MyPhpProject. Inside it I have 2 folders: Domain and Testing.
In Domain folder I have 3 PHP files:
BaseDomain.php which contains an abstract class BaseDomain
Location.php which contains a concrete class Location inherited from BaseDomain
Employee.php which contains a concrete class Employee inherited from BaseDomain
Employee class has a reference of Location class.
This is the BaseDomain.php:
<?php
abstract class BaseDomain {
}
?>
This is the Location.php:
<?php
$returnRequire = require 'BaseDomain.php';
class Location extends BaseDomain {
private $locationIdInt;
private $codeNameString;
private $descString;
public function setLocationId($locationId) {
$this->locationIdInt = $locationId;
}
public function getLocationId() {
return $this->locationIdInt;
}
public function setCodeName($codeName) {
$this->codeNameString = $codeName;
}
public function getCodeName() {
return $this->codeNameString;
}
public function setDesc($desc) {
$this->descString = $desc;
}
public function getDesc() {
return $this->descString;
}
}
?>
This is Employee.php:
<?php
$returnRequire = require 'BaseDomain.php';
class Employee extends BaseDomain {
private $employeeIdString;
private $locationObject;
public function setEmployeeId($employeeId) {
$this->employeeIdString = $employeeId;
}
public function getEmployeeId() {
return $this->employeeIdString;
}
public function setLocation($location) {
$this->locationObject = $location;
}
public function getLocation() {
return $this->locationObject;
}
}
?>
Now in the Testing folder I created a Test_Employee.php and this is its code:
<?php
set_include_path('../Domain');
$getIncludePath = get_include_path();
echo "getIncludePath = " . $getIncludePath;
echo "<br>";
$returnRequire1 = require 'Location.php';
echo "returnRequire for Location.php = " . $returnRequire1;
echo "<br>";
$returnRequire2 = require 'Employee.php';
echo "returnRequire for Employee.php = " . $returnRequire2;
echo "<br>";
?>
When I try to run it http://localhost:81/MyPhpProject/Testing/Test_Employee.php I got a fatal error regarding cannot redeclare BaseDomain class. This is what I see in browser:
getIncludePath = ../Domain
returnRequire for Location.php = 1
Fatal error: Cannot redeclare class BaseDomain in C:\Program Files
(x86)\Apache Software
Foundation\Apache2.2\htdocs\MyPhpProject\Domain\BaseDomain.php on line
2
I have not created BaseDomain class more than once. So this error is bizarre. Can somebody please explain why I am getting error message? And how to fix it.
Thanks for your time.
The line $returnRequire1 = require 'Location.php'; loads Location.php, which in turns loads BaseDomain.php in the line $returnRequire = require 'BaseDomain.php';. Then, the line $returnRequire2 = require 'Employee.php'; loads Employee.php, which loads (again) BaseDomain.php (the line $returnRequire = require 'BaseDomain.php';). The second load of BaseDomain.php causes php to try to redefine the BaseDomain class, which is no allowed.
The easiest way to solve this problem is to change your require calls to require_once. This will ensure that each file is loaded exactly once per run, which will prevent the error you are experiencing.
BaseDomain.php:
<?php
abstract class BaseDomain {
}
?>
Location.php
<?php
class Location extends BaseDomain {
private $locationIdInt;
private $codeNameString;
private $descString;
public function setLocationId($locationId) {
$this->locationIdInt = $locationId;
}
public function getLocationId() {
return $this->locationIdInt;
}
public function setCodeName($codeName) {
$this->codeNameString = $codeName;
}
public function getCodeName() {
return $this->codeNameString;
}
public function setDesc($desc) {
$this->descString = $desc;
}
public function getDesc() {
return $this->descString;
}
}
?>
Employee.php:
<?php
class Employee extends BaseDomain {
private $employeeIdString;
private $locationObject;
public function setEmployeeId($employeeId) {
$this->employeeIdString = $employeeId;
}
public function getEmployeeId() {
return $this->employeeIdString;
}
public function setLocation($location) {
$this->locationObject = $location;
}
public function getLocation() {
return $this->locationObject;
}
}
?>
Test_Employee.php
<?php
set_include_path(__DIR__.'/MyPhpProject/Domain');
require 'BaseDomain.php';
$getIncludePath = get_include_path();
echo "getIncludePath = " . $getIncludePath;
echo "<br>";
$returnRequire1 = require 'Location.php';
echo "returnRequire for Location.php = " . $returnRequire1;
echo "<br>";
$returnRequire2 = require 'Employee.php';
echo "returnRequire for Employee.php = " . $returnRequire2;
echo "<br>";
?>
Trying to get a hang of classes in php, trying to include carClass.php into new_file.php.
carClass.php
<?php
class carClass
{
private $color;
private $gear;
private $model;
private $gas;
function paintCar($carColor) {
$this->color = $carColor;
}
function findCarColor() {
echo "$color";
}
function shiftGear($newGear) {
$this->gear=$newGear;
}
function findGear() {
echo "$gear";
}
function chooseModel($newModel) {
$this->model = $newModel;
}
function findModel() {
echo"$model";
}
function fillCar($gasAmount) {
$this->gas = $gasAmount;
}
function lookAtGauge() {
echo "$gas";
}
}
?>
its just a bunch of getters and setters. Im trying to include this class to new_file.php
new_file.php
<?php
include("carClass.php");
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGuage();
?>
When I try to execute this file I get these error messages
Warning: include(carClass.php): failed to open stream: No such file or directory in C:\xampp\htdocs\testFile\new_file.php on line 4
Warning: include(): Failed opening 'carClass.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\testFile\new_file.php on line 4
Fatal error: Class 'carClass' not found in C:\xampp\htdocs\testFile\new_file.php on line 6
I believe both files are in testFile directory so I'm not sure whats going on. I appreciate any help you guys can give me as usual.
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
<?php
include_once dirname(__FILE__) . '/carClass.php';
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGuage();
?>
You can use PHP's auto loading feature which will automatically load a class when an object is created. If you have many classes then you can use it an header file so that you don't need to worry about using this include every time.
<?php
function __autoload($class_name) {
include $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Try this:
<?php
class carClass
{
private $color;
private $gear;
private $model;
private $gas;
function paintCar($carColor) {
$this->color = $carColor;
}
function findCarColor() {
echo $this->color;
}
function shiftGear($newGear) {
$this->gear=$newGear;
}
function findGear() {
echo $this->gear;
}
function chooseModel($newModel) {
$this->model = $newModel;
}
function findModel() {
echo $this->model;
}
function fillCar($gasAmount) {
$this->gas = $gasAmount;
}
function lookAtGauge() {
echo $this->gas;
}
}
?>
//
<?php
include("carClass.php");
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGauge();
?>
I'm trying to make a prototype of a simple plugin system I plan on implementing into one of my projects. I have 4 files:
Index.php
Plugins/__BASE.php
Plugins/Sample.php
The index file checks if the 'oncall' method belongs to a class in the Plugins folder using functions I defined in the Plugins class (__BASE.php). If it does exist, it will execute it.
require_once 'Plugins/__BASE.PHP';
$func = 'oncall';
$plugins = new Plugins();
if($plugins->IsPluginMethod($func)) {
$obj = $plugins->GetObject($func);
call_user_func(array($obj, $func));
}
else
echo "'$func' isn't part of a plugin!";
__BASE.php is the base plugin class which all of the plugins will extend. It has two methods: IsPluginMethod() and GetObject(). IsPluginMethod checks if the method name supplied belongs to a class and GetObject returns an instance of the class the method belongs to.
class Plugins {
public $age = "100";
public function IsPluginMethod($func) {
foreach(glob('*.php') as, $file) {
if($file != '__BASE.php') {
require_once $file;
$class = basename($file, '.php');
if(class_exists($class)) {
$obj = new $class;
if(method_exists($obj, $func))
return true;
else
return false;
}
}
}
}
public function GetObject($func) {
foreach(glob('*.php') as $file) {
if($file != '__BASE.php') {
require_once $file;
$class = basename($file, '.php');
if(class_exists($class)) {
$obj = new $class;
return $obj;
}
}
}
}
}
Sample.php is a sample plugin which prints $this->age which is defined in the Plugins class.
class Sample extends Plugins {
public function oncall() {
echo "Age: {$this->age}";
}
}
This is what I see in index.php:
'oncall' isn't part of a plugin!
Can anyone help? Thanks.
In __BASE.php file change (glob('*.php') to glob('Plugins/*.php')
I am writing a config file parser and have a function called getVals() in my Config.php file but apparently when I call it in a test it throws an "Undefined function" error.
Config.php
<?php
require_once '../extlib/pear/Config/Lite.php';
class Config {
private $config;
function __construct($conf) {
$this->config = new Config_Lite();
echo "calling open...<br>";
$this->open($conf);
echo "open done...<br>";
}
function open($cfile) {
if (file_exists($cfile)) {
$this->config->read($cfile);
} else {
file_put_contents($cfile, "");
$this->open($cfile);
}
}
function getVals() {
return $this->config;
}
function setVals($group, $key, $value) {
$this->config->set($group, $key, $value);
}
function save() {
$this->config->save();
}
}
?>
Testing class in cfgtest.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../util/Config.php';
$cfile = "../../test.cfg";
$cfg = new Config($cfile);
if (is_null($cfg)) {
echo "NULL";
} else {
echo $cfg.getVals();
}
?>
Output
calling open...
open done...
Fatal error: Call to undefined function getVals() in cfgtest.php on line 13
I would like to know why the undefined function error appears when there's the function there already.
In php to call a method or a member of an object, use the -> operator:
if (is_null($cfg))
{
echo "NULL";
}
else
{
echo $cfg->getVals();
}
Learn more on PHP Object Oriented Programming on PHP's website.
Call should be using -> operator
$cfg.getVals();
should be
$cfg->getVals();
Use $cfg->getVals(); instead of $cfg.getVals();
Now you are trying to do a concatenation !
Ooops ... missed the '->'. Lol. Good catch for all.