I have been having a hella of a time trying to get an array to initialize inside a class. What I am trying to attempt is to create a side menu using an array and a child class. I have tried to solve this problem for several days and now I'm asking for help. I have a feeling I am missing something basic as I am just learning PHP.
Below is my code and the commented out lines are attempts at a solution that have not worked.
<?php
/************* global variables ******************************/
//global $house_array, $car_array, $vacation_array, $company_address;
$company_name = "Heaven HVAC";
$street = '12345 Blue Canyon Rd.';
$company_citystatezip = "Heaven, CA 91777";
/************* end global variables **************************/
echo '<H1 align="center">Calling Array inside Child Class</H1>';
class Company{
//// insert object variables (properties) HERE
var $company_url = "http://localhost";
var $company_email = "example#example.com ";
//// insert methods here
function getHeader($company_name, $color) {
$topheader = "<TABLE align='center'; style='background-color:$color; width:50%'><TR><TD>";
$topheader .= "<H1 style='text-align:center'>$company_name</H1>";
$topheader .= "</TD></TR></TABLE>";
return $topheader;
}
function getFooter($color) {
$this->address;
$bottomfooter = "<TABLE align='center'; style='background-color:$color;width:50%'><TR><TD>";
$bottomfooter .= "<center><b><u>$this->address</center></b></u>";
$bottomfooter .= "</TD></TR></TABLE>";
return $bottomfooter;
}
} // end class Company
//// Working On child class - If commented out, then the code has been tried and failed
class AirCondition extends Company {
var $navbar_array;
//// create array
function create_navbar_array ( ) {
$mainurl = $this->company_url;
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
//create_navbar_array();
// return $navbar_array;
function getLeftNavBar($array){
// create_navbar_array();
## Create a table to display arrays
print "<TABLE BORDER='1'>";
echo '<tr><td>Navigation Menu</td></tr>';
foreach($array as $Page){
echo "<tr><td>{$Page}</td></tr>";
return $array;
}
echo "</TABLE>";
}
}
$HVACcompany = new AirCondition();
$HVACcompany->address = "777 Estate Rd <br /> $company_citystatezip";
echo $HVACcompany->getHeader($company_name, orange);
echo "<br/>";
echo $HVACcompany->getFooter(green);
//echo $HVACcompany->getLeftNavBar();
//echo $HVACcompnay->create_navbar_array();
//$HVACcompnay->create_navbar_array();
$HVACcompany->getLeftNavBar($navbar_array);
?>
I am able to create the web page layout, but the array isn't initializing. What am I doing wrong/missing?
The following line:
$HVACcompany->getLeftNavBar($navbar_array);
should be:
$HVACcompany->getLeftNavBar($HVACcompany->navbar_array);
Because $navbar_array was never declared in the global namespace, however it was declared as a public variable within the class AirCondition which was initialized with the variable $HVACcompany.
Additionally you need to call the function $HVACcompany->create_navbar_array();
before calling $HVACcompany->getLeftNavBar($HVACcompany->navbar_array); in order to create the array $navbar_array.
Also remove the return $array; statement inside the foreach loop.
Related
I'm new to PHP and have a problem. I have a navbar on the side of a homepage that displays 4 links. I'm supposed to write a method setWhichPage in a child class that will access a CGI parameter named 'whichpage' from a parent class and use it to determine which of the 4 linked pages will display in the main section of the homepage, using another method called getMainFunction. The navbar was created with the methods getLeftNavBar and createNavbarArray, which exist in the child class (called TravelAgent), but get their variables from the parent class (called Company). The method setWhichPage is supposed to be in this child class also. I'm supposed to use the value $_GET or $_REQUEST array to set the value in the property $whichpage. The acceptable values for the $whichpage property should match the getLeftNavBar method. The methods getLeftNavBar and setWhichPage work together so that when the user clicks on a link in the navbar the URL they are supposed to create these links:
http://amazingadventures.000webhostapp.com/?whichpage=home
http://amazingadventures.000webhostapp.com/?whichpage=sales
http://amazingadventures.000webhostapp.com/?whichpage=support
http://amazingadventures.000webhostapp.com/?whichpage=contact
Where I'm having trouble is when I try to get setWhichPage to set the variable $whichpage to one of the four values in the links, I get this error message:
Notice: Undefined index: whichpage in /storage/ssd1/873/8888873/public_html/index.php
Can you tell me what I'm doing wrong? Thanks in advance for any help. Here's the relevant code:
<?php
class Company { //start of parent class Company
protected $company_name;
protected $company_address;
protected $company_url;
protected $company_email;
protected $whichpage;
public function __construct(){
$this->company_name = "Amazing Adventures Travel";
$this->company_address = "13999 Turtle Way, Los Angeles, California, 90001";
$this->company_url = "http://amazingadventures.000webhostapp.com/";
$this->company_email = "email.edu";
$this->whichpage = "home";
}
//other methods...
} //end of parent class Company
class TravelAgent extends Company { //start of child class TravelAgent
var $navbar_array;
function create_navbar_array() {
$mainurl = $this->company_url;
$this->navbar_array = array("Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact");
}
function getLeftNavBar() {
echo "<table border=1, td width=100, height = 40><tr>";
foreach($this->navbar_array as $x => $x_value) {
echo '<tr><td>'. $x ."</td></tr>";
echo "<br>";
}
echo "</tr></table>";
}
function setWhichPage(){
$whichpage = $_GET['whichpage'];
}
function getMainSection() {
echo "The ".$whichpage." page";
}
}
//end of child class TravelAgent
$travelobject = new TravelAgent(); //object creation
$travelobject->getHeader(); //function calls
$travelobject->create_navbar_array();
$travelobject->getLeftNavBar();
$travelobject->setWhichPage();
$travelobject->getFooter();
?>
<table style='width:100%' border='1'> //HTML
<tr>
<td style='width:15%'>Left Navigation Bar</td>
<td> getMainSection()</td> //function call
</tr>
</table>
You have to reference it with $this->whichpage and check for $_GET['whichpage'] if is set. Something along the lines like this:
function setWhichPage(){
if(isset($_GET['whichpage'])) {
$this->whichpage = $_GET['whichpage'];
}
}
function getMainSection() {
echo "The ".$this->whichpage." page";
}
Notice: Undefined index: whichpage in /storage/ssd1/873/8888873/public_html/index.php
This error means $_GET array does not have the key whichpage.
In your case if you open http://amazingadventures.000webhostapp.com/ the $_GET array will be empty.
The best practice is to check whether the key exists before accessing.
Example of setWhichPage:
$this->whichpage = isset($_GET['whichpage']) ? $_GET['whichpage'] : $this->whichpage; // "home" by default
I am parsing a JSON Object and using a foreach loop to output the data.
function do_api_call() {
$place_id = get_theme_mod('place_id_setting_field');
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" . $place_id . "&key=myapikey";
$data = file_get_contents($url);
$rev = json_decode($data, true);
$reviews = $rev["result"]["reviews"];
foreach($reviews as $review) {
$review_snippet = $review["text"];
echo $review_snippet . '<br>';
}
}
This works fine when I call it within an HTML element with:
<?php echo do_api_call() ?>
The short of it is that I get back 5 reviews from this loop and I need each review to go to their own html element in a different file called reviews.php, this file contains 5 unique bootstrap cards with a div that needs to hold a unique review so I need to output a unique review into each of these cards.
Like so:
<div> review 1 text </div>
<div> review 2 text </div>
<div> review 3 text </div>
<div> review 4 text </div>
<div> review 5 text </div>
You access a direct review with $rev["result"]["reviews"][0] (for the first) $rev["result"]["reviews"][1] (for the second) etc. So you can pass which review as a function arg.
However to cut down on re-loading an external source with every call of the function, you may want to do the data loader outside the function:
$place_id = get_theme_mod('place_id_setting_field');
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.
$place_id .'&key=myapikey';
$data = file_get_contents($url);
$rev = json_decode($data,true);
$reviews = $rev['result']['reviews'];// this is now setup and ready to use
And then setup the anonymous function using the global (php 5.3+):
$get_review = function ($r) use (&$reviews) {
if (isset($reviews[$r])) {
return '<div>'. $reviews[$r]['text'] .'<div>';
}
return '';// no review to return
};
Then down in your html where you want to begin outputting them, you call it as such (note the $ is intentional with anonymous functions assigned to variables):
<body>
blah blah other stuff
<?php echo $get_review(0);?>
more blah
<?php echo $get_review(1);?>
</body>
Or if you need to loop on how many reviews you have:
<body>
<?php for($r=0;$r < count($reviews);$r++) { echo $get_review($r); } ?>
</body>
If you are afraid of using anonymous functions as I have above, you can adjust it to this instead:
function get_review ($r,&$reviews) {
if (isset($reviews[$r])) {
return '<div>'. $reviews[$r]['text'] .'<div>';
}
return '';// no review to return
}
// call it as thus
echo get_review(0,$reviews);
echo get_review(1,$reviews);
// etc
Class Method:
Of course you COULD also turn this into a small class object, where you first load_api, then get_review as methods of the class:
class Reviews {
public static $reviews;
public static function load_api() {
$place_id = get_theme_mod('place_id_setting_field');
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.
$place_id .'&key=myapikey';
$data = file_get_contents($url);
$rev = json_decode($data,true);
self::$reviews = $rev['result']['reviews'];// this is now setup and ready to use
}
public static function get_review($r) {
if (isset(self::$reviews[$r])) {
return '<div>'. self::$reviews[$r]['text'] .'<div>';
}
return '';// no review to return
}
}
// to initialize
Reviews::load_api();
// to call and output
echo Reviews::get_review(0);
I'm coding a small piece for a larger project that will read a CSV file and store the information in a class. I'm storing each instance of the class in an array.
So far, all I'm trying to do is read each line of the CSV, create a new class instance with that info, and then display the info using a class function I created.
I have two questions:
first, when building the constructor, I originally tried using $this->$property but I got undefined variable errors for each property when I did that. I took out $this and it seemed to work alright. I'm wondering why $this didn't work there?
And now the error that I'm having is an undefined variable error for each time I try to access a variable to print it out in the displayInfo() function of my class. I don't understand how the variable is undefined, they are properties of the class and they were initialized using the constructor.
Here's my code:
<?php
class Course {
public $crn;
public $title;
public $instructor;
public $section;
public $location;
public $time;
public $days;
function __construct($arg_crn, $arg_title, $arg_instructor, $arg_section, $arg_location, $arg_time, $arg_days) {
$crn = $arg_crn;
$title = $arg_title;
$instructor = $arg_instructor;
$section = $arg_section;
$location = $arg_location;
$time = $arg_time;
$days = $arg_days;
}
public function displayInfo() {
echo ("\n");
echo $crn;
echo (", ");
echo $title;
echo (", ");
echo $instructor;
echo (", ");
echo $section;
echo (", ");
echo $location;
echo (", ");
echo $time;
echo (", ");
echo $days;
echo ("<br/>");
}
}
?>
<?php
$fileName = "testCSV.txt";
$fp = fopen($fileName, "r");
$index = 0;
// get the next line of the CSV: this contains the headers
$fields = fgetcsv($fp);
// get the next line of the CSV, which contains the first course information
// $fields is an array holding each field of the line (where a field is separated by commas)
$fields = fgetcsv($fp);
while($fields) {
// if at the end of the file, fgetcsv returns false and the while loop will not execute
// the fields in the file are saved into the following indices in fields:
// 0: CRN
// 1: Title
// 2: Instructor
// 3: Section
// 4: Location
// 5: Time
// 6: Days
// add a new course to the array of courses using the information from fields
$Courses[$index] = new Course($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6]);
$Courses[$index]->displayInfo();
// get the next line and increment index
$fields = fgetcsv($fp);
$index++;
}
?>
As Mark Baker mentioned that instance variable can be accesses using $this->crn, follow the same & read some tutorials on OOPS in PHP as you are too new to this to ask anything here.
You tried accessing properties using $this->$property, which should be $this->property.
Some tutorials:
http://php.net/manual/en/language.oop5.php
http://www.tutorialspoint.com/php/php_object_oriented.htm
I have just started using codeigniter, PHP and facing issue while trying to build UI dynamically by fetching data from DB:
Requirement:
I need to create a list of parent - child dynamically by reading info from DB.
I have two tables admin_menu and admin_menu_item. Admin menu contains parent menu options and admin_menu_item contains each parent's detail option. admin_menu_item has AD_MENU_ID column storing parent's id giving me hierarchical structure.
My Controller:
class Home extends CI_Controller {
public function index()
{
$this->load->helper('url');
$this->load->helper('array');
$this->load->model('Menu');
$header_data['base_url'] = base_url();
$data['menu'] = $this->Menu->get_admin_menu_data();
$data['menu_item'] = array();
foreach($data['menu'] as $row){
array_push($data['menu_item'],
$this->Menu->get_admin_menu_item_data($row->ad_menu_id));
}
$this->load->view('homepage/header');
$this->load->view('homepage/admin_menu',$data);
}
}
Here is the structure of the code
My Model:
class Menu extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_admin_menu_data()
{
$this->db->select('ad_menu_id,ad_menu_name');
$query = $this->db->get('admin_menu');
return $query->result();
}
function get_admin_menu_item_data($menu_id)
{
$query = $this->db->query("SELECT ad_menu_item_name FROM ADMIN_MENU_ITEM WHERE AD_MENU_ID = " . $menu_id);
if( $query->num_rows() > 0 ){
return $query->result();
}
}
}
When I use $data variable in my view I get a blank parent row resulting in an extra item where parent doesn't have a value and I get following error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: homepage/admin_menu.php
Line Number: 9
which is basically my view line where I access parent element
My View:
echo "<ul class=\"accordion\" id=\"accordion-1\">";
foreach ($menu as $key => $value) {
print "<li class=\"dcjq-current-parent\">"; //add li tag
print "" . $value->ad_menu_name . "\n";
print "<ul>";
foreach($menu_item as $key_item => $value_item){
print "<li><a href=\"#\">";
print $value_item->ad_menu_item_name . "</a></li>\n";
$action_type = '';
}//end of menu item for each
print "</ul></li>\n";
}//end of menu for each
print "</ul>";
Sorry, for the long post but I am really stuck here and cannot figure out what is wrong with this?
Update:
I was finally able to make it work ny changing the code in model and view. The issue was objects within objects causing the hierarchy to become too complex.
The final solution was to make just one database call and process data in the view.
Thanks Yan for working with me and guiding to the solution.
It seems you have two different objects in the $menu variable in the view which is not recommened. My suggestion is to send one of them as a second parameter to the view.
Notice how you are overwriting the data in '$data['menu']['menu_item']' with each iteration of the foreach loop.
In the controller:
$data['menu_item'] = array();
foreach($data['menu'] as $row){
array_push($data['menu_item'],
$this->Menu->get_admin_menu_item_data($row->ad_menu_id));
}
In the view:
foreach ($menu_item as $key => $value) {
print "<li class=\"dcjq-current-parent\">"; //add li tag
print "" . $value->ad_menu_name . "\n";
}
EDIT:
The solution was merging the SQL queries:
SELECT ADMIN_MENU_ITEM
.ad_menu_item_name FROM ADMIN_MENU_ITEM JOIN admin_menu ON ADMIN_MENU_ITEM.AD_MENU_ID = admin_menu.ad_menu_id
i'am have same problem
how to fix error Message: Trying to get property of non-object
if i'am inject "-" from URL.
to fix edit your artikel_model.php
function get_by_id($id){
$query = $this->db->get_where('tbl_artikel', array('id' => $id));
if ($query->num_rows() > 0){
return $query->row();
}else{
print_r('No Found Artikel');
error_reporting(0);
}
}
print_r('No Found Artikel'); <-- if URL not found show this message
error_reporting(0); <-- to hiden error report
./eoc
Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details