PHP Class problems - php

I'm having troubles with this classes in PHP...
What I want is a "notification" system across my whole website - however this script only works when everything is in one file. How can I fix this.
class Message {
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();

I think you're looking for the include_once function. Essentially, you want to have each of your classes in their own separate file, and then when you want to use them, you call include_once("thatfile.php"); to make that class accessible to your application.
I should clarify that you should use include_once (or require_once if you would prefer) over include because if you include your class file twice, you'll get errors saying you're trying to define a class that already exists.
Using your example, your program would look like this:
MessageClass.php
<?php
class Message {
public $message;
// Return a string containing a list of messages found
public function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
public function addMessage($description){
$this->message[] = $description;
}
}
index.php
<?php
include_once("MessageClass.php");
$message = new Message();
$message->addMessage('Article Title 1'); $message->addMessage('Article Title 2');
$message->listMessages();
Also notice that I changed your class variables (members) and functions (methods) to include the public modifier. I'm not 100% sure about how it works in PHP, but in most languages these things tend to be private by default, meaning they can't be accessed from outside of the class. It's always better to include them to be clear.
You might also want to look into the __autoload() function, which is called whenever you try to use a class which hasn't yet been defined. In this function, which you define yourself, you can figure out in which file a given class resides, and include_once it automatically when you need it. More generally, you should look into the spl_autoload_register function, which is the same thing but with a lot more flexibility.

If you want these messages to be viewable across all pages on your site, then you need to store them somewhere permanent. Anything you put in a PHP variable ceases to exist after each page request. Put the messages in a file or a database, and read them from the database when you instantiate your Message object.

you can create one class file where this class are situated with its all methods then you have to include this class file in the all file where you want to use this class and methods.
and then you can use this class with the create an object.
Thanks.

In PHP, multiple files can be made to work together using include/require and their cousins include_once/require_once. Let me demonstrate by example. You can break things up into multiple files as follows; Put the class in a file called Message.php which might look like this:
<?php
class Message {
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
?>
And include it in another file, in the same directory called notification.php which might look like this.
<?php
require_once 'Message.php';
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();
?>

Have you tried putting your class into a seperate file
-- class.Message.php -----
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
?>
---- end class -----
--- testPageMessage.php -----
<?php
require_once('class.Message.php');
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();
?>
---- end test page -----
On a side note you may want require or include. The difference being:
REQUIRE will throw an exception if not found.
INCLUDE will throw a warning if not found.
The _ONCE (Require_once or Include_once) will make sure the file is only included once. (as opposed to multiple times)

Although, its not entirely clear from your question that the following solution may be of use, but try calling the last four lines in the footer file (which is included in every page), if you've it..
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();

Related

Cannot declare class because its already defined

I want to make my own class in php to handle my errors I want to show to the user, for example when the user are logging in but the password or username is false.
I have a map classes with the files:
errorHandling.class.php
class errorHandling
{
public $customError;
public function setCustomError($error)
{
$this->customError = $error;
}
public function getCustomError()
{
echo $this->customError;
}
}
And in the users.class.php
when the user try's to login and it fails the else will be like:
else {
include 'errorHandling.class.php';
$errorHandle = new errorHandling();
$errorHandle->setCustomError("Username or password are wrong!");
}
Then in the login.php in the root map I have this code to call the function:
include 'classes/errorHandling.class.php';
include 'classes/users.class.php';
$errorHandle = new errorHandling();
$errorHandle->getCustomError();
Well now I get this error message but I don't understand it so I hope some of you guys can helping me out or give me some tips to improve my class.
Fatal error: Cannot declare class errorHandling, because the name is already in use in /classes/errorHandling.class.php on line 1
Every time you include a file in php, it will be loaded and run. For class definitions, you want to use require_once, which as it says, will only be loaded once.

Calling a single function from another file without including the whole file in php

Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>

PHP : Can not call object method from a page which included by another method of my class

I have just created a class to control my php application, and I have one big problem ( I use 2 days for thinking and searching about it but can't find any solutions). My class contains a method named register(), which load scripts into pages. My class is:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
And in time.php file
$time = 'haha';
$apps->set($time);
As the title of my question , when I purely include time.php into main.php, I can use $apps->set($time) ($apps has been defined in main.php). Like this main.php:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
But when I call method register() from Apps class to include time.php , I got errors undefined variable $apps and call set method from none object for time.php (sounds like it doesn't accept $apps inside time.php to me) . My main.php is:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
By the way , I'm not good at writing . So if you don't understand anything just ask me. I appreciate any replies. :D
If you want your second code snippet to work, replace the content of time.php with:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
since this code is included by an instance method of the Apps class, it will have access to the instance itself, $this.

setFetchMode to type Class using namespaces in PHP

I'm trying to populate some variables in a PHP class by using setFetchMode and FETCH_CLASS.
<?php # index.php
use myproject\user\User;
use myproject\page\Page;
$q = 'SELECT * FROM t';
$r = $pdo->query($q);
// Set the fetch mode:
$r->setFetchMode(PDO::FETCH_CLASS, 'Page');
// Records will be fetched in the view:
include('views/index.html');
?>
In my view file, I have:
<?php # index.html
// Fetch the results and display them:
while ($page = $r->fetch()) {
echo "<article>
<h1><span>{$page->getDateAdded()}</span>{$page->getTitle()}</h1>
<p>{$page->getIntro()}</p>
<p>read more here...</p>
</article>
";
}
?>
These methods are from Class: Page.php:
<?php # Page.php
function getCreatorId() {
return $this->creatorId;
}
function getTitle() {
return $this->title;
}
function getContent() {
return $this->content;
}
function getDateAdded() {
return $this->dateAdded;
}
?>
It's pretty straightforward when using standard classes, that is, I've had it all working fine; name-spaces seem problematic however.
For example if I use:
<?php # index.php
require('Page.php'); // Page class
$r->setFetchMode(PDO::FETCH_CLASS, 'Page'); // works
?>
But when using namespaces,
<?php # index.php
use myproject\page\Page;
?>
// Set the fetch mode:
$r->setFetchMode(PDO::FETCH_CLASS, 'Page'); // problem
// Records will be fetched in the view:
include('views/index.html');
?>
Browse to index.php and the browser reports:
Fatal error: Call to a member function getDateAdded() on a non-object in /var/www/PHP/firstEclipse/views/index.html on line 5
My namespace paths are all set-up correctly, as I've successfully instantiated objects using the above naming conventions, for example:
<?php # index.php
use myproject\page\User; # class: /myproject/page/user/User.php
$b = new User();
print $b->foo(); // hello
?>
If you are using PHP earlier than 5.5
You need to provide the fully qualified name of the class:
use myproject\page\Page;
$r->setFetchMode(PDO::FETCH_CLASS, 'myproject\page\Page');
It's unfortunate that you have to repeat yourself like this (this code would break if you decided to switch to a different class Page from another namespace), but there is no way around the ugliness.
If you are using PHP 5.5
You are in luck! The new ::class keyword was designed to help with exactly this problem:
// PHP 5.5+ code!
use myproject\page\Page;
// Page::class evaluates to the fully qualified name of the class
// because PHP is providing a helping hand
$r->setFetchMode(PDO::FETCH_CLASS, Page::class);

Include PHP file with parameter

newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.
An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}
Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");
In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));
The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included

Categories