Usage of class in PHP from different directory - php

I have been using Classes in PHP.
I have a directory, test, In which there is index.php
A sub-directory to test is new, which has checkuser.php
Code for checkuser CODE:
<?php
public class checkuser{
public function checkuser()
{
echo "This is class";
}
}
?>
Code for index.php:
<?php include('new/checkuser.php'); ?>
<html>
<head>
</head>
<body>
<?php
checkuser::checkuser();
?>
</body>
</html>
But It always throws error.
Please Help.

What kind of error is that?
There is more things:
You are declaring the class "public"
Parse error: syntax error, unexpected T_PUBLIC on line 2
You are calling non-static method statically
Fatal error: Non-static method checkuser::checkuser() cannot be called statically on line 17
You are including the file, without being aware of the context, i suggest this practice:
<?php include( dirname(__FILE__) . '/new/checkuser.php'); ?>
or if you are using PHP > 5.3
<?php include( __DIR__ . '/new/checkuser.php'); ?>
And here is how your code could work:
<?php
class checkuser {
public static function myfunction()
{
echo "This is class";
}
}
?>
<html>
<head>
</head>
<body>
<?php checkuser::myfunction(); ?>
</body>
</html>
http://codepad.org/C9boO1lI
Note: of course, you can split your code in more files, just make sure that you specify the path as seen above, so it can find the actual file

Related

Problem with the visibility of a variable in the included layout PHP

EDIT:
According to the question: Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
should work for me, but it does not. I probably don't understand something, but I can't see where the bug is.
I'm a newbie in PHP so the question is probably simple and stupid. I have 3 files: index.php, View.php and layout.php. In View php I have a View class definition and a render() method. Among others, this method includes an HTML template from the file layout.php.
But: in the PHP file in the <main> tag I have a piece of php code (if statement) which, depending on the value of the $page variable (defined in the PHP file), includes a different file
The problem is that this variable appears as undefined in the layout.php file.
I don't understand why, in the end all code is executed in index.php: View class is included and render function includes layout.php.
Please help me understand this, because I can't do it. Thanks in advance.
Notice: Undefined variable: action in C:\xampp\htdocs\notes\templates\layout.php on line 17
index.php
<?php
declare(strict_types=1);
namespace App;
require_once("src/utils/debug.php");
require_once("src/View.php");
$action = $_GET['action'] ?? null;
$view = new View();
$view -> render($action );
View.php
<?php
declare(strict_types=1);
namespace App;
class View
{
public function render(?string $page): void
{
include_once("templates/layout.php");
}
}
layout.php
<html>
<head>
</head>
<body>
<header>
<h1>Nagłówek</h1>
</header>
<nav>
<ul>
<li><a href="index.php/?action=list">Lista notatek</li>
<li><a href="index.php/?action=create">Nowa notatka</li>
</ul>
</nav>
<main>
<?php
if ($page === 'create') {
include_once("templates/pages/list.php");
} else {
include_once("templates/pages/create.php");
}
?>
</main>
<footer>
</footer>
</body>
</html>

Problem with the visibility of a variable in the included PHP file

EDIT:
According to the question: Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
should work for me, but not. I probably don't understand something, but I can't see where the bug is. So, in my opinion, it`s not duplicate.
I'm a newbie in php so the question is probably simple and stupid. I have 3 files: index.php, View.php and layout.php. In View php I have a View class definition and a render () method in it. Among others, this method include html template from the file layout.php.
But: in the php file in the tag I have a piece of php code (if statement) which, depending on the value of the $ page variable (defined in the php file), includes a different file.
The problem is that this variable appears as undefined in the layout.php file.
I don't understand why, in the end all code is executed in index.php: View class is included and render function includes layout.php.
Please help me understand this, because I can't do it. Thanks in advance
Notice: Undefined variable: action in C:\xampp\htdocs\notes\templates\layout.php on line 17
index.php
<?php
declare(strict_types=1);
namespace App;
require_once("src/utils/debug.php");
require_once("src/View.php");
$action = $_GET['action'] ?? null;
$view = new View();
$view -> render($action );
View.php
<?php
declare(strict_types=1);
namespace App;
class View
{
public function render(?string $page): void
{
$apction = $page
include_once("templates/layout.php");
}
}
layot.php
<html>
<head>
</head>
<body>
<header>
<h1>Nagłówek</h1>
</header>
<nav>
<ul>
<li><a href="index.php/?action=list">Lista notatek</li>
<li><a href="index.php/?action=create">Nowa notatka</li>
</ul>
</nav>
<main>
<?php
if ($action === 'create') {
include_once("templates/pages/list.php");
} else {
include_once("templates/pages/create.php");
}
?>
</main>
<footer>
</footer>
</body>
</html>

Undefined variable after wrapped include in PHP

I'm using PHP for web development. I'm using the following function to wrap the include of a view:
<?php
function render($templateFile) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
?>
Although this seems right to me, there is a really unexpected behavior: when I define a variable to something (e.g. an array) and use render for including a view that uses that variable, I get an undefined variable error. But when I explicitely use include there is no error at all and things are just fine.
This is the script that calls render:
<?php
include 'lib/render.php'; // Includes the function above.
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html'); // Error, but "include 'views/names.html'" works fine.
?>
And this is the file that uses the $names variable:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($names as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
Help will be very much appreciated.
This is from the PHP documentation on the include function (c.f. http://us1.php.net/manual/en/function.include.php):
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
And also:
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function.
So, if your render function can't access $names, then neither can your included file.
A possible solution would be to pass the parameters you want to be able to access in your view template, to your render function. So, something like this:
function render($templateFile, $params=array()) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
Then, pass them like this:
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html', array("names" => $names));
And use them in your view template like this:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($params['names'] as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
There are probably better solutions to this, like putting your render function into a View class. Then you can call the View class function from inside your template file, and access parameters that way instead of just assuming there will be a $params variable in the view templates scope. But, this is the simplest solution.
The problem is, when you include the file directly using include 'views/names.html' the variable $name remains in the same files scope. Hence, it works. But when the include is done through the function, the varibale $name remains out of scope inside the function. So it doesn't work. For example, declare $names as global inside the function and it will work.
If you update the function like below you will see $names variable works.
function render($templateFile) {
global $names; // declares the global $names variable to use in the included files
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}

How to call a function inside yii framework controller from core php file?

I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.

include php file containing function in a web page

I have a php file which contains php function. I have to receive its return value in a part of my web page. Where do I put the include? in the head or in the body? how can I call the function inside my web page?
You can include the php file wherever you want, as long as it is before you call the method contained in it. You call the function between <?php ?> tags. You can use echo to output it to the page.
So if you have myfunc.php that looks like this:
<?php
function myfunc() {
return 'asdf';
}
?>
Then in php that includes it you can do:
<?php
include('myfunc.php');
echo myfunc();
?>
You can also choose to put the include method anywhere above that makes sense. The very top of the file is a common choice.
Also note that if your php file contains functions, you should probably be using require_once instead of include. See: http://php.net/manual/en/function.require-once.php
You can't call php code from a html file. However, you could simply make your html web page into a php web page like this:
<?php
include("yourphpfunction.php");
?>
<html>
<head>...</head>
<body>
....
<!-- put php result here: -->
<?php echo myfunction(); ?>
... more html
</body>
</html>
and save it as .php instead of .html.
That's all the magic.
You can also wrap it all up in one statement:
<html>
<head>...</head>
<body>
....
<!-- put php result here: -->
<?php
include("yourphpfunction.php");
echo myfunction();
?>
... more html
</body>
</html>
as long as your file gets parsed as php.
you can put the include in the top of your html page like
<?php
include 'file.php';
?>
<html>
<head>
.....
and on your HTML, you can do something like:
<div>my stactic text <?php echo myFunction(); ?></div>
You should require (require_once) the file, before you reach the part where your returned output should be echoed.
required file.php:
<?php $test = "hello world"; return $test; ?>
include include.php:
<?php $output = require_once('file.php'); echo $ouput; ?>
You need a php webpage, you can't call a php function or include a php page in html file.
Assuming your webapge is php, You can include that file in the top of the page inside the tag. But be sure to include the file before the function is called.
require_once 'path/to/your/file';
or
include_once 'path/to/your/file';
Then you can call the function in your php file like:/
$test = functionInYourIncludedFile();
echo $test;
Hope this helps you :)
look below :
<?php
function doSomthing() {
return $var
}
?>
<html>
<?php echo doSomthing() ?>
</html>
or
<?php include('functionFile.php') ?>
<html>
<?php echo doSomthing() ?>
</html>

Categories