EDITED: Added checking stops into code.
keeping OOP design, what am I doing wrong?
The triangle sides are not passing into the classes properly.
I already tested the object with parameters inside the PHP file and it's working excellent. So it seems that the only culprit here is how I'm passing the params inside the classes.
Here is my shape.php:
<?php
abstract class Shape{
abstract protected function getArea();
abstract protected function getPerimeter();
}
class Triangle extends Shape{
private $_sides = array();
private $_perimeter = null;
public $status = 0;
function __construct($s0=0, $s1=0, $s2=0){
$this->_sides[] = $s0;
$this->_sides[] = $s1;
$this->_sides[] = $s2;
echo 'constructed<hr>';
//calculate perimeter:
$this->_perimeter = array_sum($this->_sides);
echo 'calculated perimeter<hr>';
$this->checkForm();
}
public function checkForm(){
if (!empty($_POST['submit'])){
$checkIt = $this->status = 1;
/* echo 'status is <hr>'.$checkIt;*/
}
return $this->status;
}
public function proceed(){
if ($this->status == 1){
echo 'proceed func started<hr>';
$this->_sides[0] = $_POST['s0'];
$this->_sides[1] = $_POST['s1'];
$this->_sides[2] = $_POST['s2'];
echo 'Side 1: '.$this->_sides[0] = $_POST['s0'].'<hr>';
echo 'Side 2: '.$this->_sides[1] = $_POST['s1'].'<hr>';
echo 'Side 3: '.$this->_sides[2] = $_POST['s2'].'<hr>';
}else{
echo 'This didn\'t work as planned... :(';
}
}
public function getArea(){
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}
public function getPerimeter(){
return $this->_perimeter;
}
}
/*$check = new Triangle(2, 2, 2);*/
$check = new Triangle();
echo $check->proceed();
echo 'status is: '.$check->status.'<hr>';
echo 'The '.get_parent_class($check).' is a '.get_class($check).'. It\'s Perimeter is: '.$check->getPerimeter().'M.<br>';
echo 'The '.get_parent_class($check).' also has an area of: '.$check->getArea().'M.<br>';
And this is my index.php file:
<div class="row">
<div class="boxy">
<form method="post" action="Shape.php">
<label for="s0">Side 1</label>
<input name="s0" type="number" placeholder="Side 0"><br>
<label for="s1">Side 2</label>
<input name="s1" type="number" placeholder="Side 1"><br>
<label for="s2">Side 3</label>
<input name="s2" type="number" placeholder="Side 2"><br>
<input type="submit" name="submit" value="Run It.">
</form>
</div>
</div>
There are few issues with your code, such as:
You're trying to set up triangle properties in the constructor but you're not passing any values. See this statement,
$check = new Triangle();
You didn't make use of checkForm() and proceed() method.
Though there are several solutions to this problem, one would be like this:
Keep your constructor method empty, like this:
function __construct(){}
And change your proceed(), getArea() and getPerimeter() methods in the following way,
private function proceed(){
if ($this->status == 1){
$this->_sides[0] = isset($_POST['s0']) ? $_POST['s0'] : 0;
$this->_sides[1] = isset($_POST['s1']) ? $_POST['s1'] : 0;
$this->_sides[2] = isset($_POST['s2']) ? $_POST['s2'] : 0;
}else{
echo 'This didn\'t work as planned... :(';
}
}
public function getArea(){
if($this->checkForm()){
$this->proceed();
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}else{
echo "Something went wrong. ";
}
}
public function getPerimeter(){
if($this->checkForm()){
$this->proceed();
return $this->_perimeter = array_sum($this->_sides);
}else{
echo "Something went wrong. ";
}
}
Well, I actually found the error, I forgot to return the proceed() results.
Here it is amended and fully working:
abstract class Shape{
abstract protected function getArea();
abstract protected function getPerimeter();
}
class Triangle extends Shape{
private $_sides = array();
private $_perimeter = null;
public $status = 0;
function __construct($s0=0, $s1=0, $s2=0){
$this->_sides[] = $s0;
$this->_sides[] = $s1;
$this->_sides[] = $s2;
echo 'constructed<hr>';
//calculate perimeter:
$this->_perimeter = array_sum($this->_sides);
echo 'calculated perimeter<hr>';
$this->checkForm();
}
public function checkForm(){
if (!empty($_POST['submit'])){
$checkIt = $this->status = 1;
/* echo 'status is <hr>'.$checkIt;*/
}
return $this->status;
}
public function proceed(){
if ($this->status == 1){
echo 'proceed func started<hr>';
$this->_sides[0] = $_POST['s0'];
$this->_sides[1] = $_POST['s1'];
$this->_sides[2] = $_POST['s2'];
echo 'Side 1: '.$this->_sides[0] = $_POST['s0'].'<hr>';
echo 'Side 2: '.$this->_sides[1] = $_POST['s1'].'<hr>';
echo 'Side 3: '.$this->_sides[2] = $_POST['s2'].'<hr>';
}else{
echo 'This didn\'t work as planned... :(';
}
return $this->_sides;
}
public function getArea(){
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}
public function getPerimeter(){
return $this->_perimeter;
}
}
$check = new Triangle($_POST['s0'], $_POST['s1'], $_POST['s2']);
/*$check = new Triangle();*/
echo 'status is: '.$check->status.'<hr>';
echo 'The '.get_parent_class($check).' is a '.get_class($check).'. It\'s Perimeter is: '.$check->getPerimeter().'M.<br>';
echo 'The '.get_parent_class($check).' also has an area of: '.$check->getArea().'M.<br>';
Related
I need to create a work method that takes as a parameter an instance of the successor of Work. here is my code
declare(strict_types=1);
```
declare(strict_types=1);
interface Primat {
public function eat(bool $e);
public function drink(bool $d);
}
trait ofPlank{
function cofeeTime($cof){ echo 'drink cofee ';}
}
abstract class Human{
public string $name;
abstract public function work(string $work);
}
class Dev extends Human implements primat{
use ofPlank;
public $rank = array(
1=>'junior',
2=>'middle',
3=>'senior',
4=>'lead'
);
public int $rankState = 0;
public function __construct(int $currentRank)
{
$this->rankState = $currentRank;
}
public function show()
{
echo $this->rank[$this->rankState];
}
public function Up()
{
$this->rankState++;
}
public function Down()
{
$this->rankState--;
}
public function eat( $e)
{
if ($e ==1){
echo 'eat';}
else {
echo 'hungry';
}
// TODO: Implement eat() method.
}
public function drink($d)
{
if ($d ==1){
echo 'drink';}
else {
echo 'need water';
} ; // TODO: Implement drink() method.
}
use ofPlank;
public function work($work)
{
$work = 'go to work';
// TODO: Implement work() method.
}
} echo 'backend promotion from';
$backend = new Dev(1,);
echo $backend->show()."\n";
$backend->Up();
echo 'to ';
echo $backend->show()."\n";
echo '|backend need eat->';
$backend->eat($e=1);
//var_dump($backend);
echo '|ofplank ';
$backend->cofeeTime(cof );
?>
<br><?php
echo 'frontend lvl ';
$frontend = new dev(1,);
echo $frontend->show()."\n";
echo '|frontend need water->';
$backend->drink($d=2);
?>
<br>
<br>
<br>
<br>
<br>
```
I already tried to implement this task, and googled similar topics, nothing came out, I would be grateful if you tell me where to go or what to read. Thank you all for your time!
I'm working with a player class, the code prints a form with name, lastname and location fields that have to be filled in to add a new player.
But I have a problem when printing the players since I only print the names of the players, when I try to print the data separately (name, lastname and location) I do not print anything.
session_start();
class Player {
private $players;
private $name;
private $lastname;
private $location;
public function __construct($name,$lastname,$location)
{
$this->name = $name;
$this->lastname = $lastname;
$this->location = $location;
$this->players = array();
}
public function getName()
{
return $this->name;
}
public function getLastname()
{
return $this->lastname;
}
public function getLocation()
{
return $this->location;
}
public function addPlayer($onePlayer)
{
$this->players[] = $onePlayer;
return $this;
}
public function printPlayers()
{
foreach($this->players as $player){
// just show the name¿?.
echo $player.'<br />';
// The problem is here.
/*echo $player['name'].'<br />';
echo $player['lastname'].'<br />';
echo $player['location'].'<br />';*/
}
}
public function __toString()
{
return $this->name;
return $this->lastname;
return $this->location;
}
}
function printForm()
{
echo '<FORM METHOD="POST" style="text-align: center; margin-top: 73px;">
<h2>Add Players</h2>
<label>Add the name : </label><INPUT class="form" TYPE = "text" NAME = "name"> <br>
<label>Add the lastname : </label><INPUT class="form" TYPE = "text" NAME = "lastname"> <br>
<label>Add the location : </label><INPUT class="form" TYPE = "text" NAME = "location"> <br><br>
<INPUT class="form" TYPE = "submit" VALUE = "add" name="action">
<INPUT class="form" TYPE = "submit" VALUE = "list" name="action">
</ FORM>';
}
// Load the player data of the session and if it does not exist create a new player.
function loadData()
{
return isset($_SESSION['player']) ? $_SESSION['player'] : new Player();
}
// Save the player's data in the session.
function saveData($player)
{
$_SESSION['player'] = $player;
}
printForm();
$player = loadData();
if(isset($_POST['action']))
{
switch($_POST['action'])
{
case 'add':
$player->addPlayer(new Player($_POST['name'],$_POST['lastname'],$_POST['location']));
saveData($player);
break;
case 'list':
echo '<hr />';
$player->printPlayers();
break;
}
}
It looks like in the problematic part you're trying to access private properties using array syntax. That won't work for a couple of reasons
The properties aren't accessible there because they're defined as private
You can't get them with array syntax. If they weren't private you'd need to use $player->name.
But fortunately you have also written some getters, so you should be able to use those instead, like this:
echo $player->getName();
I have a class called members, i have an example below. What i am asking is how do i set the values of title. So for example , i only allow Mr, Mrs, Miss and any other values will throw out an error stating Only Mr,Mrs,Miss is allowed , Firstname must be John..
class Member
{
private $title;
private $firstname;
public function __construct( $title )
{
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member( "Mrr" );
$data->showProfile();
You can try this , hope this will be helpful.
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
throw new Exception("Only Mr,Mrs,Miss are allowed!");
//or you can simple echo out your message instead of exception
}
$this->title = $title;
}
public function showProfile()
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
}
$data = new Member("Mrr");
Optionally you can set a variable for this error with in the class, which prevent further execution of methods of class script. You can also do it like this
Solution 2:
Try this code snippet here
<?php
ini_set("display_errors", 1);
class Member
{
private $title;
private $error=false;
public function __construct($title)
{
if(!in_array($title, ["Mr","Mrs","Miss"]))
{
$this->error=true;
}
$this->title = $title;
}
public function showProfile()
{
if($this->error!==true)
{
echo "<dl>";
echo "<dt>Title:</dt><dd>$this->title</dd>";
echo "</dl>";
}
else
{
echo "Only Mr,Mrs,Miss is allowed!";
}
}
}
$data = new Member("Mrr");
$data->showProfile();
Make a setter
function setTitle($newTitle){
if(in_array($newTitle, array('Mr', 'Miss', 'Mrs' ))
$this->title=$newTitle;
else
echo 'ERROR';
}
And then call it from the constructor
I didnt like any of the answers.
Here's mine. I think you should use a mutator in your solution. The member class should be decoupled from the setter.
class Member
{
private $title;
public function setTitle($title)
{
$this->title = $title;
}
public function showProfile()
{
return sprintf("<dl><dt>Title</dt><dt><dd>%s</dd></dt></dl>" , $this->title );
}
}
class TitleProperty
{
protected $name = 'title';
protected $allowed_allowed = ['mr', 'mrs', 'miss'];
public $errors = [];
/**
*#param Member $member
*#param string $value
*/
public function __construct( Member $member, $value )
{
if(!in_array($value, $this->allowed_allowed )){
$this->errors[] = "Only Mr,Mrs,Miss is allowed";
}
else{
$member->setTitle( $value );
}
}
}
$member = new Member();
$property = new TitleProperty($member, 'hello');
if($property->errors){
print_r($property->errors);
}
else{
echo 'title set.';
}
There you go
I want to display the number of the table, which I get from the HTML form, in this method: private function getComanda();.
I use public function displayMethod() to call the private function getComanda().
I want the table number to be displayed in the class Table, in the public function setMasa($nr_masa), which has a switch. It is not displaying anything at all.
When I try to display the table number with this function from Shop class, public function getProperty(), it works. I am stuck, can anyone help?
I tried to make the function getProperty() as both private and protected and it did not show any results, but if I change it to public it does.
This is the HTML code:
<html>
<body>
<form action="" method="post">
<p>Preturi:</p><br/>
Nr-Masa: <input type="text" name="nr_masa" /><br/>
<input type="submit" value="Trimite" name="submit_masa" />
</form>
</body>
</html>
The class shop where:
$nr_masa=number of table; $_masa1=table1
class Shop
{
protected $nr_masa;
private $_masa1;
public function setComanda($nr_masa)
{
$this->_nr_masa = $nr_masa;
}
public function displayMethod()
{
$this->_masa1=$this->getComanda();
print $this->_masa1;
}
private function getComanda()
{
return "<br /><br />Table number:" . $this -> _nr_masa . "<br />";
}
public function getProperty()
{
return $this -> _nr_masa . "<br />";
}
}
class Table extends Shop
{
public function setMasa($nr_masa)
{
switch($nr_masa) {
case "1";
echo "Masa Nr.1 a fost rezervata";
echo $this -> displayMethod();
break;
case "2";
echo "Masa Nr.2 a fost rezervata";
echo $this -> displayMethod();;
break;
case "3";
echo "Masa Nr.3 a fost rezervata";
echo $this -> displayMethod();
break;
case "4";
echo "Masa Nr.4 a fost rezervata";
echo $this -> displayMethod();
break;
default:
echo "Masa nu exista";
}
}
}
$TabelData = new Table;
$ShopData = new Shop;
if (isset($_POST['submit_masa'])) {
$nr_masa = $_POST["nr_masa"];
$TabelData -> setMasa($nr_masa);
$ShopData -> setcomanda($nr_masa);
}
you are using print in function displayMethod() and then using echo in function setMasa
public function displayMethod()
{
$this->_masa1=$this->getComanda();
return $this->_masa1; <-- replace print with return;
}
I have a Class to manage the users and everything was working fine until I had to add more columns to the table and modify 2 names. Now one of the modified names, the function that returns the column content is not working, the colum is fill with data but it's not printing anything when I call the function.
I rechecked many times the code, looking for a bad typed name or something, but everything seems to be fine, I can't find the problem...
This is my class:
require_once('aet.php');
class staff {
private $aet;
private $not_working_column;
private $working_column;
public function __construct() {
$this->aet = new aet();
}
private function generate($staff) {
$this->not_working_column = $staff->not_working_column;
$this->working_column = $staff->working_column;
}
private function addInformation($stmt) {
$i = 0;
$stmt->bind_result($not_working_column, $working_column);
while ($stmt->fetch()) {
$arrayStaff[$i] = new staff();
$arrayStaff[$i]->setNotWorkingColum($not_working_column);
$arrayStaff[$i]->setWorkingColumn($working_column);
$i++;
}
}
public function StaffFromEmail($email) {
$mysqli = $this->aet->getAetSql();
if ($stmt = $mysqli->prepare("SELECT * FROM staff WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
$exit = false;
}
else {
$arrayStaff = $this->addInformation($stmt);
$this->generate($arrayStaff[0]);
$exit = true;
}
}
return $exit;
}
public function setNotWorkingColum($not_working_column) {
$this->not_working_column = $not_working_column;
}
public function getNotWorkingColum() {
return $this->not_working_column;
}
public function setWorkingColumn($working_column) {
$this->working_column = $working_column;
}
public function getWorkingColumn() {
return $this->working_column;
}
}
And in the form where users can update their info
<div class="item">
<div class="input">
<input type="text" placeholder="" name="staff_info[]" value="<?php echo $staff->getNotWorkingColum(); ?>" />
</div>
</div>
<div class="item">
<div class="input">
<input type="text" placeholder="" name="staff_info[]" value="<?php echo $staff->getWorkingColumn(); ?>" />
</div>
</div>
I've also made a video https://www.youtube.com/watch?v=9S_Uw7IK_xY
My fault, while changing the name of a column I missed one:
public function setPersonalPhone($personal_phone) {
$this->phone = $personal_phone;
}
Should be:
public function setPersonalPhone($personal_phone) {
$this->personal_phone = $personal_phone;
}