Here is my code. I do not know why creating new object name site create an error. also the name of the file for my object is the same as the class name site.php.
<?php
class site {
var $is_container_enabled = 1;
function init() {
$this->container_tpl = "common/common";
}
function handle_page($page) {
$this->cache_id = $page;
$this->smarty->caching = 0;
switch ($page) {
case "static" :
$type=$_REQUEST['choice'];
$this->default_tpl = "static/$type";
break;
default :
$this->is_container_enabled = isset($_REQUEST['ce'])?$_REQUEST['ce']:1;
$this->default_tpl = $page.'/home';
break;
}
}
function is_container_enabled(){
return $this->is_container_enabled;
}
function set_container_enabled($ce){
$this->is_container_enabled = $ce;
}
function get_container_tpl(){
return $this->container_tpl;
}
}
some index.php that call the object site
echo "before site declaration";
$site = new site; // cause error
echo "after site declaration";
$site->init();
$smarty = getSmarty();
$site->smarty= &$smarty;
$site->cache_id= &$cache_id;
Result in the browser image
And here is also
Console error image
include 'site.php';
echo "before site declaration";
$site = new site; // You can access member variables/functions with this
echo "after site declaration";
$site->init();
$smarty = getSmarty();
$site->smarty= &$smarty;
$site->cache_id= &$cache_id;
Try this
As per #Quasimodo's clone mentions in the comments, you need to make sure that you are including the class in the file that you are trying to execute:
use site; // if you are using namespacing
include 'path/to/site'; // if you want to directly include the file
require 'path/to/site'; // same as include but will throw an E_COMPILE_ERROR if it wasn't found
echo "before site declaration";
$site = new site;
echo "after site declaration";
If it turns out you are already including the file then consider commenting out all of the methods in the site class and seeing if it still fails to instantiate. It could be that you have some syntax error in your class.
Related
I want to include a class from file own.php but I am not able to include it as it giving me error as require(class.own.php): failed to open stream: No such file or directory .
I tried all the options i.e include, require, require_once but then also it showing me a error.
include("class/own.php");
own.php
<?php
class own{
public function title(){
$title = $_POST['title'];
echo $title;
}
}
?>
display.php
include("class/own.php");
$obj = new own;
$obj->title();
Your directory structure should be like this
display.php
class/own.php
Then try to include
include("class/own.php");
The use
$obj = new own(); OR $obj = new \own();
$obj->title();
use this:
<?php
class own {
function title() {
$this->model = $_POST['title'];
}
}
// create an object
$test = new own();
// show object properties
echo $test->model;
?>
I think the two files are in the same path (directory), so you are including wrong path. It might be include("own.php");
Considering the following directory structure.
|directory
display.php
own.php
display.php
<?php
include("own.php");
$obj = new own;
$obj->title();
?>
I think you are confusing PHP. To include the file the following code may help
include (__DIR__)."/own.php";
While upgrading to PHP7, I encountered these problem.
The issue is am trying to create codes that I can reuse like a mini-framework and the RUN function where the problem is used to load the relevant template and supplying the variables. It complains about
undefined index
of these 2 variables
$controller = $routes[$this->route][$this->method]['controller'];
$action = $routes[$this->route][$this->method]['action'];
and it also complained about this line
$page = $controller->$action();
which displayed
Fatal error: Uncaught Error: Method name must be a string in...
public function run() {
$routes = $this->routes->getRoutes();
$authentication = $this->routes->getAuthentication();
if (isset($routes[$this->route]['login']) && !$authentication->isLoggedIn()) {
header('location: /login/error');
}
else if (isset($routes[$this->route]['permissions']) && !$this->routes->checkPermission($routes[$this->route]['permissions'])) {
header('location: /login/permissionserror');
}
else {
$controller = $routes[$this->route][$this->method]['controller'];
$action = $routes[$this->route][$this->method]['action'];
$page = $controller->$action();
$title = $page['title'];
if (isset($page['variables'])) {
$output = $this->loadTemplate($page['template'], $page['variables']);
}
else {
$output = $this->loadTemplate($page['template']);
}
echo $this->loadTemplate('layout.html.php', ['loggedIn' => $authentication->isLoggedIn(),
'output' => $output,
'title' => $title
]);
}
This is the index.php
try {
include __DIR__ . '/../includes/autoload.php';
$route = ltrim(strtok($_SERVER['REQUEST_URI'], '?'), '/');
$entryPoint = new \Ninja\EntryPoint($route, $_SERVER['REQUEST_METHOD'], new \Ijdb\IjdbRoutes());
$entryPoint->run();
}
catch (PDOException $e) {
$title = 'An error has occurred';
$output = 'Database error: ' . $e->getMessage() . ' in ' .
$e->getFile() . ':' . $e->getLine();
include __DIR__ . '/../templates/layout.html.php';
}
The code is much, so, I can't display the whole code here since am using MVC pattern, but if there is anything you still want to know, I will gladly post it here
This code is runnable in php 7.2.7 (MAMP and LAMP), your way of dynamic function calling is invalid and your two variables are empty. This is not exact as yours but you can take logic form this demo.
Ok i am just providing a very simple example of reflection with mapping url to class along with functions. I make folder structure like below-
Here .htaccess is used to redirect all the url to index.php (if no file exists).
index.php include all code that could initialize code(for now only three files were there - uri.php, urlMapping.php and actions.php)
URI.php - have function that provide values like basepath, baseurl, uri
urlMappig.php - that allows you to provide which url hit which class along with method
actions.php will call dynamic class and function (reflection)
now look into code of index.php
<?php
include_once('URI.php');
include_once('urlMapping.php');
include_once('actions.php');
?>
aNow code insise uri.php file -
<?php
// all function should be accessible to all file loaded now
// return full url
function full_url (){
return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
// returns current directory
function directory() {
$parts = explode("/", __DIR__);
return $parts[count($parts)-1];
}
// return base url
function base_url(){
$dir = directory();
return substr(full_url(), 0, strpos(full_url(), $dir)+strlen($dir));
}
// return uri
function uri() {
return substr(full_url(), strlen(base_url())+1);
}
?>
Now code in urlMapping.php
Note - file name and name of the class must be same as you map url in
this file so that you can make call to dynamic classes and function on actions.php. If don't this will not work
<?php
// this $urlMap will be accessed in actions.php
$urlMap = [
// here we use only uri so .. https://example.com/login hit LoginController class along with login function, this is just only the mapping
'login' => ['class'=>'LoginController',
'function'=>'login'],
];
?>
Now actions.php code
<?php
// if call is not like example.com/ means no uri is there
if(uri()!='')
{
// if your uri exists in route collection or urlmapping collection then make call to your dynamic class and methods
if(array_key_exists(uri(), $urlMap))
{
// include the class file dynamically from controllers folder
include_once('controllers/'.$urlMap[uri()]['class'].'.php');
// making references for dynamic class
$controlerObject = new $urlMap[uri()]['class']();
// call function dynaically from the referece
$controlerObject->{$urlMap[uri()]['function']}();
}
else
{
// you can make 404 page not
echo 'No routing found';
}
}
// call for home page
else
{
include_once('index.html.php');
}
?>
Now controllres/LoginController.php class,
Note - As mentioned above file name and name of the class as in urlMapping.php
<?php
class LoginController{
public function login()
{
// .... something your code goes here
echo 'hello from the login function of login controller';
}
//...... other function you can define
}
?>
Before calling $page = $controller->$action(); check if controller and action are exists:
if (isset($routes[$this->route][$this->method]['controller'])
&& isset($routes[$this->route][$this->method]['action'])) {
$controller = $routes[$this->route][$this->method]['controller'];
$action = $routes[$this->route][$this->method]['action'];
$page = $controller->$action();
// ...
} else {
// return 404 Page not found
}
I have a strange bug at the moment in my web service I am coding.
When I am loading an specific url I get a success and error at the same time?
This is what I have in my index.php:
<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "API Version not valid";
exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "Endpoint not valid";
exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
exit();
}
// load endpoint class and make an instance
try {
require_once($classFilePath);
$instance = new $endPoint($requestParts);
} catch (Exception $e) {
httpResponseCode(500);
echo $GLOBALS['http_response_code'];
exit();
}
and this is the corresponding "Tickets.php"
<?php
echo "OK";
?>
In the last two rows of my index.php, I am loading the specific class (named in the URL). For testing purposes, I have an "echo "OK" in this file. And this is the result when I am loading the URL I need:
http://api.medifaktor.de/v1/tickets
OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45
I get the OK I was expecting AND the error for the Class Tickets, that is not found. Line 45 is
$instance = new $endPoint($requestParts);
Can someone give me a helping hand?
Best
Sebastian
The problem is that you don't have a class "Tickets" defined. After you load the tickets.php file, you are attempting to instantiate a class. Loading a file is not the same thing as defining a class. Within tickets.php (or some other included file), you need to define the class, like so:
class Tickets
{
// some properties here
private $endpoint;
// some methods here
public function __construct($endpoint)
{
$this->endpoint = $endpoint;
}
}
If you're not sure how to construct classes in PHP, read the section in the manual on classes.
Update: I added some example code within the class for version PHP5+.
Try the following for your test, in the 'ticket.php' file add:
class Ticket {
public function __construct()
{
echo 'testing';
}
}
Then make sure you either namespace or require the file.
I have a class similar to this
class x {
function __construct($file){
$this->readData = new splFileObject($file);
}
function a (){
//do something with $this->readData;
}
function b(){
//do something with $this->readData;
}
}
$o = new x('example.txt');
echo $o->a(); //this works
echo $o->b(); //this does not work.
it seems if which ever method called first only works, if they are called together only the first method that is called will work. I think the problem is tied to my lack of understand how the new object gets constructed.
The construct is loaded into the instance of the class. And you're instantiating it only once. And accessing twice. Are different actions. If you want to read the file is always taken, should create a method that reads this file, and within all other trigger this method.
I tested your code and it worked normal. I believe it should look at the logs and see if any error appears. If the file does not exist your code will stop.
Find for this error in your apache logs:
PHP Fatal error: Uncaught exception 'RuntimeException' with message 'SplFileObject::__construct(example.txt): failed to open stream
Answering your comment, this can be a way:
<?php
class x {
private $defaultFile = "example.txt";
private function readDefaultFile(){
$file = $this->defaultFile;
return new splFileObject($file);
}
function a (){
$content = $this->readDefaultFile();
return $content ;
}
function b(){
$content = $this->readDefaultFile();
return $content ;
}
}
$o = new x();
echo $o->a();
echo $o->b();
Both methods will return an object splFile.
I am trying to assign a variable to a class in PHP, however I am not getting any results?
Can anyone offer any assistance? The code is provided below. I am trying to echo the URL as shown below, by first assigning it to a class variable.
class PageClass {
var $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
$page->get_absolute_path(); //this should echo the URL as defined above - but does not
It also works for me.
Take a look at a live example of your code here.
However, there are a few things you should change about your class.
First, Garvey does make a good point that you should not be using var. That's the older PHP4, less OOP conscious version. Rather declare each variable public or private. In fact, you should declare each function public or private too.
Generally, most classes have private variables, since you usually only want to change the variables in specific ways. To achieve this control you usually set several public methods to allow client functions to interact with your class only in restricted predetermined ways.
If you have a getter, you'd probably want a setter, since these are usually used with private variables, like I described above.
A final note is that functions named get usually return a value. If you want to display a value, it is customary to use a name like display_path or show_path:
<?php
class PageClass
{
private $absolute_path = NULL;
public function set_absolute_path($path)
{
$this->absolute_path = $path;
}
public function display_absolute_path()
{
echo $this->absolute_path;
}
}
$page = new PageClass();
$page->set_absolute_path("http://localhost:8888/smile2/organic/");
$page->display_absolute_path();
// The above outputs: http://localhost:8888/smile2/organic/
// Your variable is now safe from meddling.
// This:
// echo $this->absolute_path;
// Will not work. It will create an error like:
// Fatal error: Cannot access private property PageClass::$absolute_path on ...
?>
Live Example Here
There's a section on classes and objects in the online PHP reference.
class PageClass {
public $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
return $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo $page->get_absolute_path();
Works fine for me.
Have you checked that the script and esp. the code in question is executed at all?
E.g. add some unconditional debug-output to the script. Or install a debugger like XDebug to step through the code and inspect variables.
<?php
class PageClass {
var $absolute_path = NULL; // old php4 declaration, see http://docs.php.net/oop5
function get_absolute_path() { // again old php4 declaration
$url = $this->absolute_path;
echo "debug: "; var_dump($url);
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo "debug: page->get_absolute_path\n";
$page->get_absolute_path();