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
Related
I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError
There must be some misunderstanding with my implementation of the function $get_ship_class -> check_array($category,$cat_in_class = array()); because it's throwing the error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to
function get_ship_class::check_array(), 0 passed in
C:\xampp\htdocs\php_sandbox\assign_ship_class.php on line 60 and at
least 1 expected in
C:\xampp\htdocs\php_sandbox\assign_ship_class.php:45 Stack trace: #0
C:\xampp\htdocs\php_sandbox\assign_ship_class.php(60):
get_ship_class->check_array() #1 {main} thrown in
C:\xampp\htdocs\php_sandbox\assign_ship_class.php on line 45
in response, I tried $get_ship_class->check_array($category, $cat_in_class = array()) and it didn't work.
Essentially the first function get_class_categories() retrieves the product categories under a specific shipping class as an array.
function get_product_category($category) retrieves the category of the current product at hand - we will pretend; set $category = "Monitors" in this case.
Lastly check_array(); just checks if $category = Monitors matches any elements in the list of categories for this shipping class, which was generated by the get_class_categories() function.
<?php
class get_ship_class
{
public function get_class_categories()
{
$csv = array_map("str_getcsv", file("Shipping Classes.csv"));
/*
print_r($csv);
echo "<br />";
*/
$header = array_shift($csv);
// Separate the header from data
/*
print_r($header);
echo "<br />";
*/
$col = array_search("Com1_34-95", $header);
/*
print_r($col);
*/
foreach ($csv as $row) {
$array[] = $row[$col];
}
$cat_in_class = array_filter($array);
print_r($cat_in_class);
//https://stackoverflow.com/a/30909191/9095603
$this->check_array($cat_in_class); // pass array onto function below
}
public function get_product_category()
{
$this->category = 'Monitor';
//echo $this->category;
}
public function check_array($category, $cat_in_class = array())
{
// https://stackoverflow.com/a/6431836/9095603
//$this->category='Monitor';
$this->category;
if (in_array($this->category, $cat_in_class)) {
echo "Match detected!";
}
}
}
$get_ship_class = new get_ship_class();
$get_ship_class->get_product_category('Monitors');
//echo '<br />';
$get_ship_class->get_class_categories();
//echo '<br />';
$get_ship_class->check_array();
I agree with #u_mulder. Regardless, I'm trying to give you an answer.
Your code calls the check_array function twice:
At the end of the get_class_categories function, handing over exactly one argument: $cat_in_class - not TWO
At the end of your php file, handing over null arguments.
I suggest you to perform a code review. Once you have identified the control flow, you should be able to fix it. (Please let getXX functions return a value, if they don't name they setXX and let they write their results to object variables...)
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.
Let's say I have a class called product which has 2 properties, pid and quantity.
Now, I want to make a session that will hold an array of this class. Code example:
<?php
public class product{
public $quantity;
public $pid;
public function __construct($pid,$qty){
$this->$pid = $pid;
$this->$quantity = $qty;
}
// some methods ....
}
session_start();
$_SESSION['products'][] = new product(103,10);
$_SESSION['products'][] = new product(87,6);
?>
Few questions about this:
Is my way of declaring the sessions is correct? I haven't typed something like $_SESSION['product'] = new array(); I already added objects to it.
When I will want to read the session product, will I have to import the class product to the page in order to read it and get an access to the quantity and the pid properties?
Code example:
session_start();
echo $_SESSION['products'][0]->$pid; // should echo "103" (according the the code exmaple above)
// OR I will have to do it like this:
require_once 'product.inc.php';
session_start();
echo $_SESSION['products'][0]->$pid; // should echo "103"
3.when I access a public property, do I have to access it like this: $this->$prop_name OR $this -> prop_name (difference is with the $ sign)
if you define a variable like $var = array(); it will wipe the previous array.
sessions are available throughout your domain/sub-domain, so as long as you have called session_start() before you access the session variable you're covered.
when you say public property are you referring to the class or the method? If you want to access the method inside itself to refer to it like $this->myFunction = $object; if you want to access the method outside itself but inside the class you do it using SELF::$object = new myFunction();
see this: When to use self over $this?
and this: http://php.net/manual/en/language.oop5.php
hope this helps.
Is my way of declaring the sessions is correct?
Yes. Once you have executed the session_start() the $_SESSION array will exist and be populated with data if any has been saved into previously.
When I want to read the session product, will I have to import the class product to the page in order to read it and get an access to the quantity and the pid properties?
Yes, if you have methods you need to have the class declared in order to use them.
There is a better way of dehydrating and rehydrating a class. That is serialize() and unserialize(). It takes care of all the public, protected and private data, and it also stores the class name. It does not save the methods of course.
Here is some sample code using your original example as a start point. You can run it in your browser to see the results
file product.class.php
<?php
class product{
public $quantity;
public $pid;
private $a = 99;
protected $b = 88;
public function __construct($p,$q){
$this->pid = $p;
$this->quantity = $q;
}
public function show() {
echo '<pre>SHOW '. $this->pid . '</pre>';
}
}
?>
file tst99.php
require_once( 'product.class.php' );
session_start();
$p1 = new product(103,10);
$p2 = new product(87,6);
unset( $_SESSION['products'] );
$_SESSION['products'][] = serialize($p1);
$_SESSION['products'][] = serialize($p2);
echo 'Dehydrated class'.PHP_EOL;
echo '<pre>' . print_r( $_SESSION, TRUE ) . '</pre>';
?>
file tst99a.php
<?php
session_start();
require_once('product.class.php');
echo '<pre>' . print_r( $_SESSION, TRUE ) . '</pre>';
echo 'Rehydrated class'.PHP_EOL;
$np1 = unserialize($_SESSION['products'][0]);
$np2 = unserialize($_SESSION['products'][1]);
echo '<pre>' . print_r( $np1, TRUE ) . '</pre>';
echo '<pre>' . print_r( $np2, TRUE ) . '</pre>';
$np1->show();
$np2->show();
Run tst99.php first and then tst99a.php to see that the class gets fully rehydrated.
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