I am trying to call a function called displaySentence() and have it output the value of the 'sentence' typed into the form on candycontest.php. The function will eventually have more features, but for now I am just trying to echo out the value of that sentence to ensure the function works. When I run the script, the pages displays until it gets to my function, at which point it is blank.
candycontest.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pete's Treats Candy Contest</title>
</head>
<body>
<form action="checkticket.php" method="post">
<label for="ticketNum">Enter your ticket number:</label>
<input type="number" name="ticketNum" style="width:100px"><br/>
<label for="sentence">Enter the magic sentence:</label>
<input type="text" name="sentence" style="width:600px"><br/>
<input type="submit" value="Am I a Winner?">
</form>
</body>
</html>
checkticket.php
<?php
$userTicket = $_POST['ticketNum'];
class MagicSentence {
public $sentence;
public function __construct($sentence) {
$this->setSentence($sentence);
}
public function getSentence() { return $this->sentence; }
public function setSentence($sentence) {
$this->sentence = $sentence;
}
} // End class MagicSentence
class Ticket extends MagicSentence {
public $ticketNum;
public function displaySentence() {
$userSentence = $_POST['sentence'];
echo $userSentence;
}
}
$magicSentence = new MagicSentence("The cow jumped over the moon.");
?>
<html>
<head>
<meta charset="utf-8">
<title>Pete's Treats Candy Contest</title>
</head>
<body>
<?php
echo 'Your ticket number is: ' . $userTicket . "<br>";
echo 'The magic sentence is: ' . $magicSentence->getSentence() . "<br>";
displaySentence();
?>
</body>
</html>
Change $magicSentence = new MagicSentence("The cow jumped over the moon."); to $magicSentence = new Ticket("The cow jumped over the moon.");
You need to do this because the displaySentence() method exists under the Ticket class (which extends off the MagicSentence class).
Also, change displaySentence(); to $magicSentence->displaySentence(); in order to call your method. You cannot call a method as you would a regular function.
Do that and you should be golden.
Create an object of class Ticket, $ticketObj and use $ticketObj->displaySentence(); in place of displaySentence();
displaySentence(); is a method of the Ticket class, of which you never instantiated an object, so it doesn't exist in any context yet.
$magicSentence = new MagicSentence("The cow jumped over the moon.");
needs to be:
$magicSentence = new Ticket("The cow jumped over the moon.");
and
displaySentence(); needs to be: $magicSentence->displaySentence();
Related
I have a database where there is a table named member. Member has different columns like mem_id mem_image, mem_thumbnail, mem_phone, mem_email, city_name etc. There are more than 200 entries in this table amounting to 200 different mem_ids.
I have a php function inside a class which I use to execute the mysql query.
class myClass{
public function __construct(){}
public function memDetails($conn,$cityName)
{
global $memId;
global $memImage;
global $memThumb;
global $memPhone;
global $memEmail;
$sql = "SELECT * FROM member WHERE mem_id=$memId";
$mem_details = $this->query($conn,$sql);
foreach ($mem_details as $setValue) {
$memId= $setValue->mem_id;
$memImage= $setValue->mem_image;
$memThumb= $setValue->mem_thumbnail;
$memPhone= $setValue->mem_phone;
$memEmail= $setValue->mem_email;
}
}
Now in the Php front end page where I want to display the data, I first create an object of the class myClass and then call the function memDetails
<html>
<head>
</head>
<body>
// database connection code here
$obj = new myClass();
$obj->memDetails($conn, $memId);
<p>Image URL= <?PHP echo $memImage ?></p>
<p>Thumb URL= <?PHP echo $memThumb ?></p>
<p>Phone= <?PHP echo $memPhone ?></p>
<p>Email= <?PHP echo $memEmail ?></p>
</body>
</html>
The reason I am doing this is because I need to use this function in different pages to retrieve the data for member. And that is exactly why I have declared the variables as global so that I can use them in all pages after I call that function. But as I have heard it is not wise to use global as it gets difficult to keep track of all global variables and also one change in its name will need me to change it across all pages.
So which is the way by which I can do this better and efficient and need less of php code in the front end php page.
There are a few loose ends in your question, but to keep things simple, I'd advise you to return something from memDetails method. For example
class myClass{
public function __construct(){}
public function memDetails($conn,$memId)
{
$result=[];
$sql = "SELECT * FROM member WHERE mem_id=$memId";
$mem_details = $this->query($conn,$sql);
foreach ($mem_details as $setValue) {
$result['memId'] = $setValue->mem_id;
$result['memImage'] = $setValue->mem_image;
$result['memThumb'] = $setValue->mem_thumbnail;
$result['memPhone'] = $setValue->mem_phone;
$result['memEmail'] = $setValue->mem_email;
}
return $result;
}
}
would return an associative array, so you could later do
<html>
<head>
</head>
<body>
// database connection code here
$obj = new myClass();
$result = $obj->memDetails($conn, $memId);
<p>Image URL= <?PHP echo $result['memImage'] ?></p>
<p>Thumb URL= <?PHP echo $result['memThumb'] ?></p>
<p>Phone= <?PHP echo $result['memPhone'] ?></p>
<p>Email= <?PHP echo $result['memEmail'] ?></p>
</body>
</html>
That way, myClass doesn't need to know anything about the vars in the outer or global scope whatsoever.
There are other ways to go about this. Each $setValue attribute could, instead, be assigned to a member variable, but then you would need to keep different instances of myClass to avoid mixing the results. In this solution you only instance myClass once and then you can reuse memDetails over and over again with different $memId.
I am trying to get a function from class to another file but when I run the code it says " Fatal error: Call to a member function start_order() on a non-object in C:\AppServ\www\store\start.php on line 4"
This is the calling code:
<?php
#session_start();
require_once ( 'include/functions.php' );
$users->start_order();
?>
And this is the class and the function code:
<meta charset='utf-8' />
<?php
require_once ( 'include/config.php' );
class users {
public function start_order () {
if($_SESSION['id']) {
$services=mysql_query("SELECT * FROM services");
print ("
<form action='<?php echo $PHP_SELF; ?>' method='post'>
<input name='orderlink' type='text'></input>
<input name='orderquantity' type='text'></input>
<input name='ordersubmit' type='text'></input>
</form>
");
$order_submit=$_POST ['ordersubmit'];
$order_link=$_POST ['orderlink'];
$order_quantity=$_POST ['orderquantity'];
if($order_submit AND !empty($order_link) AND !empty($order_quantity)){
while ($fetch_services=mysql_fetch_object($services)) {
print ("<select>");
print ("<option value='$fetch_services->id'>$fetch_services->service_name ($fetch_services->service_price)</option>");
print ("</select>"); }
} else { echo "خطاء";}
$s_id=$_POST ['service'];
$g_s_i=mysql_query("SELECT * FROM services WHERE id='$s_id'");
$fetch_service=mysql_fetch_object($g_s_i);
$s_price=$fetch_service->servic_price;
$service_n=$fetch_service->service_name;
$charge=$s_price/$order_quantity*$order_quantity;
$date=date ("Y-m-d");
$userbalance=mysql_query("SELECT * FROM users WHERE id='$_SESSION[id]'");
$fetch_userbalance=mysql_fetch_object($userbalance);
$u_balance=$fetch_userbalance->balance;
if ($u_balance >= $charge) {
$insert_order_values=mysql_query("INSERT INTO orders(id,u_id,u_name,date,link,charge,quantity,service_name,status) VALUES ('','$_SESSION[username]','$date','$order_link','$charge','$order_quantity','$service_n','0')");
$update_balance=mysql_query("UPDATE users SET balance=$u_balance-$charge WHERE id='$_SESSION[id]'");
}
else { echo "not enough fund";}
}}}
?>
You haven't made $users yet.
$users = new users();
$users->start_order();
Also, it's good practice to capitalize your class names, so they don't look so much like your instance.
$users = new Users();
$users->start_order();
You need to create an instance of the object before using it:
<?php
#session_start();
require_once ( 'include/functions.php' );
$users = new users();
$users->start_order();
?>
Is it possible to use functions within the heredoc template without breaking it?
Somethig like this:
<<<HTML
<div> showcaptcha(); </div>
HTML;
Specifically i wanna require another template in this one without using variables.
Or is there another and more simple solution that is not using heredoc?
Thx in advanced.
For example im using class named requires.
class requires {
public function __construct(){
$this->MYSQL();
$this->FUNC();
}
public function MAIN_MENU() {
require_once ('main-menu.tpl');
}
}
Then what i do in index.php
require_once ('requires.php');
$req = new requires();
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
//bla bla
</head>
<nav><ul class="fancynav">
{$req->HEAD_SCRIPTS()}
</ul></nav>
HTML;
main-menu.tpl
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
And in result i have an empty field without php error
<nav><ul class="fancynav">
</ul></nav>
WTF?
Yes, you can use the "encapsed var" trick:
function hello() {
global $result;
$result = 'hi there!';
return 'result';
}
echo <<<EOF
text ${hello()} text
EOF;
Technically, this works, but it's better to avoid hacks like this in production. A temporary variable will be much cleaner.
Since you cannot directly call a function inside HEREDOC, you may put the function name in a variable, and use that variable inside the HEREDOC string:
$showcaptcha= 'showcaptcha';
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
So you can leave the current already coded function:
function showcaptcha()
{
return "Gotta captcha mall";
}
You could also use:
$showcaptcha = function()
{
return "Gotta captcha mall";
}
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
If the function to call is defined at the same level as the echo (else, you'll have a global variable $showcaptcha).
If you have several functions, you can make a loop before the heredoc:
function dawg()
{
return "I'm loyal";
}
function cat()
{
return "I'm cute";
}
function fish()
{
return "I'm small";
}
function elephant()
{
return "I'm big";
}
$functionsToCall = array('elephant', 'fish', 'cat', 'dawg');
foreach ($functionsToCall as $functionToCall)
$$functionToCall = $functionToCall;
echo
<<<HTML
<br/> Dawg: {$dawg()}
<br/> Cat: {$cat()}
<br/> Fish: {$fish()}
<br/> Elephant: {$elephant()}
HTML;
That's way less ugly than using a global variable
No, it is not possible to use function inside heredoc strings.
I have an object in PHP with 5 attributes using the following code:
<?php
class Person
{
private $gender, $race, $height, $weight, $eyes_color;
public function start ($gender,$race,$height, $weight, $eyes_color)
{
$this->gender=$gender;
$this->race=$race;
$this->height=$height;
$this->weight=$weight;
$this->eyes_color=$eyes_color;
}
public function show_attributes()
{
return sprintf("%s, %s, %s, %s, %s", $this->gender, $this->race, $this->height, $this->weight,$this->eyes_color);
}
}
$person=new person();
?>
I'm calling this class using the following HTML code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Class Person</title>
</head>
<body>
<?php
require_once("Person.php");
$person->start("Male","Latin","1.83 cm","85 kg","Brown");
echo $person->show_attributes();
?>
</body>
</html>
Now, that will print something like
Male, Latin, 1.83 cm, 85 kg, Brown
But I want to print something like
--------------------------------------
|Male | Latin | 1.83 cm | 85 kg | Brown|
--------------------------------------
Using a HTML table.
I have try a couple of things, but I can't make it happend.
Is there a way to force
echo $person->show_attributes();
to only show one attribute so I can call it from inside a HTML cell table?
Thanks.
Try this
<?php
class Person
{
private $gender, $race, $height, $weight, $eyes_color;
public function start ($gender,$race,$height, $weight, $eyes_color)
{
$this->gender=$gender;
$this->race=$race;
$this->height=$height;
$this->weight=$weight;
$this->eyes_color=$eyes_color;
}
public function show_attributes()
{
return sprintf("<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $this->gender, $this->race, $this->height, $this->weight,$this->eyes_color);
}
}
$person=new person();
?>
HTML code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Class Person</title>
</head>
<body>
<?php
require_once("Person.php");
$person->start("Male","Latin","1.83 cm","85 kg","Brown");
echo "<table>":
echo "<tr>";
echo $person->show_attributes();
echo "</tr>";
echo "</table>";
?>
</body>
</html>
I don't know how in-depth you're looking to go, but you can load the data into a data modeler/table system like http://backgridjs.com.
I realize that may be completely over the top for what you're looking for, but it's robust and (mostly) easy to learn.
Hi I created two file to switch my forum (Language Chinese and English)
enForum.php
<?php
function foo() {
global $_COOKIES;
setcookie('ForumLangCookie', 'en', time()+3600, '/', '.mysite.com');
echo 'running<br>';
$_COOKIES['ForumLangCookie'] = 'en';
bar();
} // foo()
function bar() {
global $_COOKIES;
if (empty($_COOKIES['ForumLangCookie'])) {
die('cookie_name is empty');
}
echo 'Language =' . $_COOKIES['ForumLangCookie'];
echo "<br>";
} // bar()
foo();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>forum EN Version</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
please be patient ...
<script LANGUAGE='javascript'>
location.href='http://www.mysite.com/forum/index.php';
</script>
</body>
</html>
cnForum.php
<?php
function foo() {
global $_COOKIES;
setcookie('ForumLangCookie', 'cn', time()+3600, '/', '.mysite.com');
echo 'running<br>';
$_COOKIES['ForumLangCookie'] = 'cn';
bar();
} // foo()
function bar() {
global $_COOKIES;
if (empty($_COOKIES['ForumLangCookie'])) {
die('cookie_name is empty');
}
echo 'Language =' . $_COOKIES['ForumLangCookie'];
echo "<br>";
} // bar()
foo();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>forum CN Version</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
please be patient ...
<script LANGUAGE='javascript'>
location.href='http://www.mysite.com/forum/index.php';
</script>
</body>
</html>
There are some files including include template('logon');,include template('regist'); etc, I write some code to get the Cookie value and control the flow to load different template files.
$lang = $_COOKIE["ForumLangCookie"];
// for Debug
// echo '$lang is '.$lang;
// echo '<br/>';
if ($lang == "cn"){
include template('logon');
}
else if ($lang == "en"){
include en_template('logon');
}
But sometime the SetCookie() not working. Do I need add Sleep(someSeconds); for my code?
Cookies can be accessed with $_COOKIE,not $_COOKIES.
EDIT:Sorry for misunderstanding. I suggest you to change the variable $_COOKIES as another common one so people can understand your question correctly.
PHP array name is $_COOKIE, not $_COOKIES