call a method from a class in php - php

This is kind of embarrassing but I having problems calling a method from a class in PHP, this is how it goes: I have created a class persona with its respectives properties, the code is
<?php
class persona {
private $id;
private $nombre; //varchar(50)
private $correo; //varchar(50)
private $especialidad; //varchar(50)
private $nacionalidad; //varchar(50)
private $sueldo; //float
private $isss; //float
private $afp; //float
//getter
public function getId() {
return $this->id;
}
public function getNombre() {
return $this->nombre;
}
public function getCorreo() {
return $this->descripcion;
}
public function getEspecialidad(){
return $this->especialidad;
}
public function getNacionalidad(){
return $this->nacionalidad;
}
public function getSueldo(){
return $this->sueldo;
}
public function getIsss(){
return $this->isss;
}
public function getAfp(){
return $this->afp;
}
//setter
public function setNombre($nombre) {
$this->nombre = $nombre;
}
public function setCorreo($correo) {
$this->correo = $correo;
}
public function setEspecialidad($especialidad){
$this->especialidad=$especialidad;
}
public function setNacionalidad($nacionalidad){
$this->nacionalidad=$nacionalidad;
}
public function setSueldo($sueldo){
$this->sueldo=$sueldo;
}
public function setIsss($isss){
$this->isss=$isss;
}
public function setAfp($afp){
$this->afp=$afp;
}
public function __construct($nombre, $correo, $especialidad, $nacionalidad, $sueldo, $isss, $afp, $id=null) {
$this->nombre = $nombre;
$this->correo = $descipcion;
$this->especialidad = $especialidad;
$this->nacionalidad = $nacionalidad;
$this->sueldo = $sueldo;
$this ->isss = $isss;
$this->afp = $afp;
$this->id = $id;
}
public function mostrar(){
$mensaje="hola";
return $mensaje;
}
}
?>
as you can see at the end of the code I have created a function called mostrar, the only purpose of this is to show a message, now I want to call this method from a diferent class, my code is
<?php
require_once('persona.php');
class prueba{
private $person;
public function __construct(){
$person= new persona("el nombre","el correo", "la especialidad", "la nacionalidad", "el sueldo", "el isss", "el afp");
mostrando();
}
public function mostrando(){
$person->mostrar();
}
}
?>
but when I debug it doesn' show anything in the browser, I want to display the message from the class person.php, could you please tell me what is the problem in my code?

Variable scope:
$person !== $this->person
class prueba{
private $person;
public function __construct(){
$this->person= new persona("el nombre","el correo", "la especialidad", "la nacionalidad", "el sueldo", "el isss", "el afp");
$this->mostrando();
}
public function mostrando(){
echo $this->person->mostrar();
}
}
$this->person is an object property, accessible from all methods in the class.
$person is a local variable, accessible only from the method/function in which it is defined (unless passed as an argument to other methods/functions)

Related

Getting Uncaught Error: Call to undefined method Vehicles::setPassengerSeats()

I am getting this error:
uncaught error call to undefine method
Vehicles::setPassengerSeats() in
C:\xampp\htdocs\practice\vehicle.php:91.
I also have added screenshot of the error. Kindly check and tell me how can i solve it ? I think i have problem with my sub class but i don't know where?
Here is my source code:
<?php
class Vehicles{
private $noOfVehicles;
private $color;
private $fuel;
private $speed;
public function getNoOfVehicles(){
return $this->noOfMobiles;
}
public function setNoOfVehicles($Vehicles){
$this->noOfMobiles = $Vehicles;
echo "No of Vehicles are: ".$this->noOfVehicles."</br>";
}
public function getColor(){
return $this->color;
}
public function setColor($look){
$this->color = $look;
echo "</br>The Color of Vehicle is: ".$this->color."</br>";
}
public function getFuel(){
return $this->fuel;
}
public function setFuel($petrol){
$this->fuel = $petrol;
echo "</br>The fuel is: ".$this->color."</br>";
}
public function getSpeed(){
return $this->speed;
}
public function setSpeed($vehicleSpeed){
$this->speed = $vehicleSpeed;
echo "</br>The speed of vehicle is: ".$this->speed."</br>";
}
}
class PassengerVehicles extends Vehicles{
private $passengerSeats;
public function getPassengerSeats(){
return $this->passengerSeats;
}
public function setPassengerSeats($seats){
return $this->passengerSeats = $seats;
echo "</br>Passenger Seats are: ".$this->passengerSeats."</br>";
}
}
class TransportationVehicles extends Vehicles{
private $noOfDoors;
private $loadCapacity;
public function getNoOfDoors(){
return $this->noOfDoors;
}
public function setNoOfDoors($doors){
return $this->noOfDoors = $doors;
echo "</br>The No of Doors are: ".$this->noOfDoors."</br>";
}
public function getLoadCapacity(){
return $this->loadCapacity;
}
public function setLoadCapacity($capacity){
return $this->loadCapacity = $capacity;
echo "The Load Capacity is: ".$this->loadCapacity."</br>";
}
}
$VehiclesObj = new Vehicles;
$VehiclesObj->setNoOfVehicles("15");
$VehiclesObj->setColor("Black");
$VehiclesObj->setFuel("5 Litre");
$VehiclesObj->setSpeed("120 km/h");
$VehiclesObj->setPassengerSeats("4");
$VehiclesObj->setNoOfDoors("4");
$VehiclesObj->setLoadCapacity("500 KG");
?>
You call method setPassengerSeats which is in another class not in Vehicles You should create instance first, then to call this method:
$passangerVehicle = new PassengerVehicles;
$passangerVehicle->setPassengerSeats("4");
You can't call child methods from a parent. You need to create an instance of the child to be able to call parent methods
class Vehicles{
private $noOfVehicles;
private $color;
private $fuel;
private $speed;
public function getNoOfVehicles(){
return $this->noOfMobiles;
}
public function setNoOfVehicles($Vehicles){
$this->noOfMobiles = $Vehicles;
echo "No of Vehicles are: ".$this->noOfVehicles."</br>";
}
public function getColor(){
return $this->color;
}
public function setColor($look){
$this->color = $look;
echo "</br>The Color of Vehicle is: ".$this->color."</br>";
}
public function getFuel(){
return $this->fuel;
}
public function setFuel($petrol){
$this->fuel = $petrol;
echo "</br>The fuel is: ".$this->color."</br>";
}
public function getSpeed(){
return $this->speed;
}
public function setSpeed($vehicleSpeed){
$this->speed = $vehicleSpeed;
echo "</br>The speed of vehicle is: ".$this->speed."</br>";
}
}
class PassengerVehicles extends Vehicles{
private $passengerSeats;
public function getPassengerSeats(){
return $this->passengerSeats;
}
public function setPassengerSeats($seats){
return $this->passengerSeats = $seats;
echo "</br>Passenger Seats are: ".$this->passengerSeats."</br>";
}
}
class TransportationVehicles extends Vehicles{
private $noOfDoors;
private $loadCapacity;
public function getNoOfDoors(){
return $this->noOfDoors;
}
public function setNoOfDoors($doors){
$this->noOfDoors = $doors;
echo "</br>The No of Doors are: {$this->noOfDoors}</br>";
return $this->noOfDoors;
}
public function getLoadCapacity(){
return $this->loadCapacity;
}
public function setLoadCapacity($capacity){
return $this->loadCapacity = $capacity;
echo "The Load Capacity is: ".$this->loadCapacity."</br>";
}
}
$truck = new TransportationVehicles();
$truck->setNoOfVehicles("15");
$truck->setColor("Black");
$truck->setFuel("5 Litre");
$truck->setSpeed("120 km/h");
$truck->setNoOfDoors("4");
$truck->setLoadCapacity("500 KG");
$taxi = (new PassengerVehicles())->setPassengerSeats('4');
In this case, you will have two instances of the Vehicles class + own child.
The first instance is related to the Vehicle itself + transport properties like $noOfDoorsand $loadCapacity - a truck for example.
The second is an instance of a passenger based vehicle - taxi for example.
And you tried to get passengers option of a taxi from a bus.

convert object of class into string

class Person
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
}
class Business
{
protected $staff;
public function __construct(Staff $staff)
{
$this->staff = $staff;
}
public function hire(Person $person)
{
$this->staff->add($person);
}
public function getStaffMembers()
{
return $this->staff->members();
}
}
class Staff //staff é uma coleção, logo os membros são um array
{
protected $members = [];
public function __construct($members = [])
{
$this->members = $members;
}
public function add(Person $person)
{
$this->members[] = $person;
}
public function members()
{
return $this->members;
}
}
$daniel = new Person('Daniel Santos'); //name==$daniel santos
$staff = new Staff([$daniel]);
$laracasts = new Business($staff);
$laracasts->hire(new Person("Jorge"));
var_dump($laracasts->getStaffMembers());
I would like to print(implode("",$laracasts->getStaffMembers()); instead of just var_dump() it. Thanks.
Add a __toString "magic method" to your Person class.
class Person
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}
__toString provides a string representation of the class, so you can use it in string contexts, like echo $person, or echo implode(', ', $laracasts->getStaffMembers());
In this example I just returned the person's name, but you can do more complex stuff in that method as well (formatting, etc.), as long as it returns a string.

Backendless PHP Call to a member function on a non-object

I have been trying to retrieve data from backendless database using PHP but i get this error.
I followed the documentation but there is no much details written.
I have been trying to retrieve data from backendless database using PHP but i get this error.
I followed the documentation but there is no much details written.
Below is my code
<?php
require_once('Plant.php');
use backendless\Backendless;
include "vendor/backendless/autoload.php";
Backendless::initApp('API-KEY', 'API-KEY', 'v1');
$first_contact = Backendless::$Persistence->of('Plant')->findFirst();
$first_contact->getName();
<?php
class Plant {
private $userId;
private $tempLimit;
private $name;
private $lightLimit;
private $lastWatered;
private $humidityLimit;
private $currentTemp;
private $currentHumidity;
private $currentLight;
public function __construct() {
}
public function getName() {
return $thsi->name;
}
public function setName( $name ) {
$this->name = $name;
}
public function getUserId() {
return $thsi->userId;
}
public function setUserId( $userId ) {
$this->userId = $userId;
}
public function gettempLimit() {
return $thsi->tempLimit;
}
public function setTempLimit( $tempLimit ) {
$this->tempLimit = $tempLimit;
}
public function getLightLimit() {
return $thsi->lightLimit;
}
public function setLightLimit( $lightLimit ) {
$this->lightLimit = $lightLimit;
}
public function getLastWatered() {
return $thsi->lastWatered;
}
public function setLastWatered( $lastWatered ) {
$this->lastWatered = $lastWatered;
}
public function getHumidityLimit() {
return $thsi->humidityLimit;
}
public function setHumidityLimit( $humidityLimit ) {
$this->humidityLimit = $humidityLimit;
}
public function getCurrentTemp() {
return $thsi->currentTemp;
}
public function setCurrentTemp( $currentTemp ) {
$this->currentTemp = $currentTemp;
}
}

Class PHP methods get and set

I have this class:
<?php
class Test {
private $_ID;
private $_NAME;
private $_AGE;
public function setID() { $this->_ID++; }
public function getID() { return $this->_ID; }
public function setNAME($element) { $this->_NAME = $element; }
public function getNAME() { return $this->_NAME; }
public function setAGE($element) { $this->_AGE = $element; }
public function getAGE() { return $this->_AGE; }
public function addUser($name, $age) {
Test::setID();
Test::setNAME($name);
Test::setAGE($age);
echo "OK";
}
}
?>
I want to create objects of this class, and assign the data with the function addUser like this:
$test = new Test();
$test:: addUser("Peter", "12"); but I have errors.
I have this errors:
Strict Standards: Non-static method Test::addUser() should not be
called statically in /var/www/public/testManu.php on line 13
Strict Standards: Non-static method Test::setID() should not be called
statically in /var/www/public/class/Test.php on line 18
Fatal error: Using $this when not in object context in
/var/www/public/class/Test.php on line 8
I have problems with variable scope. Could somebody tell me what it is my problem????
change this:
...
public function addUser($name, $age) {
$this->setID();
$this->setNAME($name);
$this->setAGE($age);
echo "OK";
}
...
Calling like Classname::function() is only valid for static methods. You have a dedicated instance which need to be addressed with the construct $this->function().
And thus:
...
$test->addUser("Peter", "12"); but I have errors.
$test = new Test();
$test -> addUser("Peter", "12"); #now no errors
This should work for you:
<?php
class Test {
private static $_ID = 1;
private static $_NAME;
private static $_AGE;
public static function setID() { self::$_ID++; }
public static function getID() { return self::$_ID; }
public static function setNAME($element) { self::$_NAME = $element; }
public static function getNAME() { return self::$_NAME; }
public static function setAGE($element) { self::$_AGE = $element; }
public static function getAGE() { return self::$_AGE; }
public static function addUser($name, $age) {
self::setID();
self::setNAME($name);
self::setAGE($age);
echo "OK";
}
}
$test = new Test(); /*You don't need to instantiate the class
because you're calling a static function*/
$test:: addUser("Peter", "12"); but I have errors.
?>

PHP data collector engine Fatal Error

I am trying to write a small engine in PHP to handle data but i keep on getting this error:
Fatal error: Class 'Factory\dataHandler' not found in /Applications/MAMP/htdocs/Imperial/lp/php/dataPhraserController.php on line 12
Been now trying to find a way of solving the problem but not luck.....
My code:
DataFactory.php
<?php
namespace Factory;
class dataHandler{
protected $firstName;
protected $lastName;
protected $email;
protected $confirmEmail;
protected $phoneNumber;
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setConfirmEmail($confirmEmail)
{
$this->confirmEmail = $confirmEmail;
}
public function setPhoneNumber($phoneNumber)
{
$this->phoneNumber = $phoneNumber;
}
public function getFirstName()
{
var_dump($this->firstName);
}
public function getLastName()
{
return $this->lastName;
}
public function getEmail()
{
return $this->confirmEmail;
}
public function getPhoneNumber()
{
return $this->phoneNumber;
}
}
dataPharserController.php:
<?php
namespace PhraserController;
use Factory\dataHandler;
class DataPhraser
{
private $object;
public function __construct()
{
$this->object = new dataHandler;
}
public function pharseFirstName()
{
if(!isset($_POST['first_name']))
{
$this->object->setFirstName($firstName = null);
var_dump($_POST['first_name']);
}else{
$this->object->setFirstName($firstName = $_POST['first_name']);
}
}
}
$test = new DataPhraser();
$test->pharseFirstName();
The idea is to collect data from a submitted html form, can someone help me.. thx
Place this in one of your config files that are loaded before everything
DEFINE('LIB_DIR', '/path_to_library_dir_of_project/');
function AutoloadDefault($ClassName)
{
$File = LIB_DIR.'/' . $ClassName. '.php';
// echo 'Default:'.$File.'<br/>';
if (file_exists($File))
{
require_once($File);
}
}
spl_autoload_register('AutoloadDefault');
Then just point to right LIB_DIR folder. spl_autoload_register will load the class file

Categories