In php, i would like to call the initialized properties of the class while calling function with arguments but can't seem to figure it out. Below is my source code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Task 25 NOvember 2015</title>
</head>
<body>
<?php
class Task{
public $name = "abc";
public $fname = "xyz";
public $dob = "10-9-90";
public $country = "country";
public $ddress = "Street";
public $cgpa = 3;
public $degree = "MCS";
public $year = "2014";
public function method1($arg1, $arg2, $arg3){
$this->name = $arg1;
$this->fname = $arg2;
$this->dob = $arg3;
return "My name is ".$this->name." ".", and my father name is ".$this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4,$arg5){
}
public function method3(){}
public function method4(){}
public function method5(){}
}
$object1 = new Task();
echo $object1->method1("","","");
?>
</body>
</html>
I'm a new php programmer, I would like to figure out how I can make the initialized properties of the class to the function arguments that echo that initialized values when calling functions through objects of that class.
You are replacing the initial values to empty string in you code:
echo $object1->method1("","","");
try :
<?php
class Task
{
public $name = "Naveed";
public $fname = "Zahid";
public $dob = "10-04-1991";
public $country = "Pakistan";
public $ddress = "shergarh mardan kpk";
public $cgpa = 3.83;
public $degree = "MCS";
public $year = "2014";
public function method1($arg1, $arg2, $arg3) {
$this->name = $arg1;
$this->fname = $arg2;
$this->dob = $arg3;
return "My name is " . $this->name . " " . ", and my father name is " . $this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4, $arg5) {
}
public function method3() {
}
public function method4() {
}
public function method5() {
}
}
$object1 = new Task();
echo $object1->method1("Naveed", "Zahid", "10-04-1991");
?>
Or if you really need to use the initialized values, do not put arguments and do not overwrite the initial values:
<?php
class Task
{
public $name = "Naveed";
public $fname = "Zahid";
public $dob = "10-04-1991";
public $country = "Pakistan";
public $ddress = "shergarh mardan kpk";
public $cgpa = 3.83;
public $degree = "MCS";
public $year = "2014";
public function method1() {
return "My name is " . $this->name . " " . ", and my father name is " . $this->fname;
//i want to print the above values ... without giving in the function args
}
public function method2($arg4, $arg5) {
}
public function method3() {
}
public function method4() {
}
public function method5() {
}
}
$object1 = new Task();
echo $object1->method1();
?>
Also, try to learn more about basic/advance of PHP. you can start using this link: http://www.tutorialspoint.com/php/ tutorialspoint help me alot when studying new language
Related
Here is my sample code Class User but not working when I added the static method with the public methods:
<?php
namespace App\Classic;
class User
{
public $username;
public static $upassword;
public $age;
public $message;
public function username($username)
{
$this->username = $username;
echo $this->username."<br>";
return $this;
}
public static function password($upassword)
{
self::$upassword = $upassword;
echo self::$upassword."<br>";
}
public function age($age)
{
$this->age = $age;
echo $this->age."<br>";
return $this;
}
public function message($message)
{
$this->message = $message;
echo $this->message."<br>";
return $this;
}
}
and this is the side effect of chaining method:
$user = new User();
$user::password('secret')
->username('admin')
->age(40)
->message('lorem ipsum');
I dont know what is the logic behind doing this, but still this solution will be helpful.
Try this code snippet here
<?php
namespace App\Classic;
ini_set('display_errors', 1);
class User
{
public $username;
public static $upassword;
public static $currentObject=null;//added this variable which hold current class object
public $age;
public $message;
public function __construct()//added a constructor which set's current class object in a static variable
{
self::$currentObject= $this;
}
public function username($username)
{
$this->username = $username;
echo $this->username . "<br>";
return $this;//added this statment which will return current class object
}
public static function password($upassword)
{
self::$upassword = $upassword;
echo self::$upassword . "<br>";
return self::$currentObject;
}
public function age($age)
{
$this->age = $age;
echo $this->age . "<br>";
return $this;
}
public function message($message)
{
$this->message = $message;
echo $this->message . "<br>";
return $this;
}
}
$user = new User();
$user::password('secret')
->username('admin')
->age(40)
->message('lorem ipsum');
I am learning php now using code academy website but some is not explained properly.
These are the conditions:
Create a class called Cat.
Add two public properties to this class: $isAlive ought to store the value true and $numLegs should contain the value 4.
Add a public $name property, which gets its value via the __construct() or.
Add a public method called meow(), which returns "Meow meow".
Create an instance of the Cat class, which has the $name "CodeCat".
Call the meow() method on this Cat and echo the result.
This is the code created :
<!DOCTYPE html>
<html>
<head>
<title> Challenge Time! </title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<p>
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct() {
$cat->name = $name;;
}
public function meow(){
return "Meow meow";
}
}
$cat = new Cat(true ,4 , CodeCat);
echo $cat->meow();
?>
</p>
</body>
</html>
There's three mistakes:
__constructor without parameters
Using undefined variable $cat inside constructor instead of
$this
CodeCat should be string 'CodeCat'
Working code should look something like this:
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct($isAlive,$numLegs,$name) {
$this->name = $name;
$this->isAlive = $isAlive;
$this->numLegs = $numLegs;
}
public function meow(){
return "Meow meow";
}
}
$cat = new Cat(true ,4 , 'CodeCat');
echo $cat->meow();
?>
In your code you have a constructor with no parameters, so $name will be undefined. And when you want to create a new object Cat you call it with 3 params, but you don't have a constructor like that.
What you want is to have a constructor with 1 param $name and call it with that param like this:
<?php
// Your code here
class Cat {
public $isAlive = true;
public $numLegs = 4;
public $name ;
public function __construct($name) {
$this->name = $name;
}
public function meow(){
return $this->name;
}
}
$cat = new Cat('CodeCat'); //Like this you will set the name of the cat to CodeCat
echo $cat->meow(); //This will echo CodeCat
?>
I am trying to make a basic class that stores a name string variable. The problem is that the setName function is not working properly for me. I am getting the error:
Catchable fatal error: Method TesterClass::__toString() must return a string value in C:\xampp\htdocs\CA18\testerPage.php on line 12
I have tried many different ways of doing this, but nothing seems to fix it: The code is as follows:
<?php
class TesterClass
{
public $name;
public function setName($n)
{
$name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs == 0)
{
setName($args[0]);
}
}
}
?>
Here is the class implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payroll</title>
</head>
<body>
<h1>Payroll</h1>
<?php
require "TesterClass.php";
$myObject = new TesterClass("Philllip");
echo $myObject;
?>
</body>
</html>
Thanks!
Do this:
public function setName($n)
{
$this->$name = $n;
}
$this represents any instance of the class($myObject in your case) while $name alone is a new variable.
I think your check also is wrong.
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs == 0)//This condition says that there are no args passed so it should give an error
{
//no args
}
else $this->setName($args[0]);
}
In setName() you are setting it to a local variable $name not the $name variable in the class ... you need to use $this->name. You also need to reference $this->setName() and when you check for the number of args, you are looking for when there are 0 ... you should be looking for when there are more than 0.
class TesterClass
{
public $name;
public function setName($n)
{
$this->name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs)
{
$this->setName($args[0]);
}
}
}
<?php
class TesterClass
{
public $name = ''; // make sure this is a string!
public function setName($n)
{
$this->name = $n;
}
public function __toString()
{
return $this->name;
}
public function __construct()
{
$numArgs = func_num_args();
$args = func_get_args();
if (count($numArgs)) // if there is an arg!
{
$this->setName($args[0]); // class methods are called with $this!
}
}
}
I dont know why you are using func_get_args, but you could also just use a named parameter, with a default value.
public function __construct($name = '')
{
$this->setName($name);
}
Your code is
public function setName($n)
{
$name = $n;
}
But it should be
public function setName($n)
{
$this->name = $n;
}
In the first code, you are setting a local scope variable named "name" in setName function.
In the last code, you are setting the object property named "name".
Also you should check if it is a valid string value, AND, your property should have an string default value. Otherwise, you may get same error if you did not set name and try to get name.
How do I initialize objects inside a function within a class? so I can call each object like page[0]->getTitle(); or page[1]->getDescription();
The error now says :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\class.page.php on line 92
index.php
Page::createObjects();
and my page.class.php
private title;
private description;
private page;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public static function createObjects(){
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$this->page[$i] = new self("Title", "Description");
}
}
You might consider having two different classes here, Page (page.class.php) and Pages (pages.class.php). Your Page class will represent an individual page record from your database, and your Pages class will contain methods that work on a set of records.
page.class.php
<?php
class Page
private title;
private description;
public function __construct($title="", $description=""){
$this->title = $title;
$this->description = $description;
}
public function getTitle()
{
return $this->title;
}
public function getDescription()
{
return $this->description();
}
}
?>
pages.class.php
<?php
class Pages
public static function createObjects(){
$pages = array();
$database = new database();
$database->query('SELECT * FROM pages');
for($i=0;$i<$totalRows;$i++){
//line 92 here
$pages[] = new Page("Title", "Description");
}
return $pages;
}
}
?>
Then in your index.php, you get your Page objects from Pages
index.php
<?php
$pages = Pages::createObjects();
// to get the title of the first object
echo $pages[0]->getTitle();
?>
Like others commented, you can't access $this from a static function
a static field/variable/property/method belong to the class, not to a specific instance
<?php
class VIP
{
private $name, $surname;
private static $vips = array();
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
self::$vips[] = $this;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
static function getAll(){
return self::$vips;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
echo $a->getCredentials() . "\n";
foreach(VIP::getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
demo: https://eval.in/161874
however, this is more than likely bad code, since you are a beginner you should forget of static fields and methods and just use regular ones
better code:
<?php
class VIP
{
private $name, $surname;
function __construct($name, $surname){
$this->name = $name;
$this->surname = $surname;
}
function getCredentials(){
return $this->name . ", " . $this->surname;
}
}
class VIPsList
{
private $storage = [];
function add(VIP $vip){
$this->storage[] = $vip;
}
function getAll(){
return $this->storage;
}
}
$a = new VIP("George", "Clooney");
$b = new VIP("Scarlet", "Johansson");
$c = new VIP("Brad", "Pitt");
$d = new VIP("Emma", "Stone");
$collection = new VIPsList();
$collection->add($a);
$collection->add($b);
$collection->add($c);
$collection->add($d);
echo $a->getCredentials() . "\n";
foreach($collection->getAll() as $vip)
echo $vip->getCredentials() . "\n";
?>
https://eval.in/161898
Hello guys I'm new to PHP's OOP so I need a little help from my test scripts.
This is what I've tried so far:
index.php
<?php
include("shared.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Car Details</title>
</head>
<body>
<?php
$car1 = new Car("Audi");
echo $car1->showCarDetails();
?>
</body>
</html>
car.php
<?php
class Car extends CarDetails {
public $name;
public $color = "Freaking Sexy White";
public $price = "PHP 4,000,000.00";
public function _construct($name) {
$this->setName($name);
$this->getColor();
$this->getPrice();
}
public function setName($name) {
$this->name = $name;
}
public function setColor($color) {
$this->color = $color;
}
public function setPrice($price) {
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getColor() {
return $this->color;
}
public function getPrice() {
return $this->price;
}
public function showCarDetails() {
print nl2br("I have an awesome car. Below are the details :)\r\n".
"Brand: " . $this->getName() . "\r\n" .
"Model: " . parent::getModel(). "\r\n" .
"Color: " . $this->getColor() . "\r\n" .
"Price: " . $this->getPrice()
);
}
}
?>
cardetails.php
<?php
class CarDetails {
public $model = "A7 Sportback";
public $engine = "FSI technology";
public function setModel($model) {
$this->model = $model;
}
public function getModel() {
return $this->model;
}
public function setEngine($engine) {
$this->engine;
}
public function getEngine() {
return $this->getEngine;
}
}
?>
shared.php
<?php
function __autoload($className)
{
//echo "We are requesting the " . $className . " class";
if(file_exists($className . ".php"))
{
require_once($className . ".php");
//echo "The " . $className . " has been included";
}
}
?>
I want to access the method from my parent class which is CarDetails.php, getModel() and getEngine(). But I don't know how to do that, and also what I have declared in the constructor of Car.php in my index.php is not found.
The output:
Notice: Object of class Car could not be converted to int in C:\xampp\htdocs\oop\cardetails.php on line 13
I have an awesome car. Below are the details :)
Brand:
Model: 1
Color: Freaking Sexy White
Price: PHP 4,000,000.00
But my intended output should be:
I have an awesome car. Below are the details :)
Brand: Audi
Model: A7 Sportback
Color: Freaking Sexy White
Price: PHP 4,000,000.00
What is the problem in my code? Any ideas? I'd truly appreciate your help. Thanks.
UPDATE:
I can now access the methods from my parent class. But the problem is, I'm not seeing anything that I declared in my constructor.
Brand: __
Where it should be:
Brand: Audi
Since I passed in "Audi" in index.php
You have a couple of typos in cardetails.php:
public function setEngine($engine) {
$this->engine;
}
public function getEngine() {
return $this->getEngine;
}
should instead be
public function setEngine($engine) {
$this->engine = $engine;
}
public function getEngine() {
return $this->engine;
}
Also, in car.php:
public function _construct($name) {
should be
public function __construct($name) {
I believe that's causing the weirdness you're seeing.
So I've made a few changes here, the whole point behind extending your class is so that your child class HAS the public/protected functionality that the parent class had.
This would mean that your child class Car shouldn't need to call parents when accessing the getModel or any other functions.
You can see the code changes run live here, https://ideone.com/vCfxYQ
<?php
class Car extends CarDetails {
public $name;
public $color = "Freaking Sexy White";
public $price = "PHP 4,000,000.00";
public function __construct($name) {
$this->setName($name);
$this->getColor();
$this->getPrice();
}
public function setName($name) {
$this->name = $name;
}
public function setColor($color) {
$this->color = $color;
}
public function setPrice($price) {
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getColor() {
return $this->color;
}
public function getPrice() {
return $this->price;
}
public function showCarDetails() {
print nl2br("I have an awesome car. Below are the details :)\r\n".
"Brand: " . $this->getName() . "\r\n" .
"Model: " . $this->getModel(). "\r\n" .
"Color: " . $this->getColor() . "\r\n" .
"Price: " . $this->getPrice()
);
}
}
class CarDetails {
public $model = "A7 Sportback";
public $engine = "FSI technology";
public function __construct() {
}
public function setModel($model) {
$this->model = $model;
}
public function getModel() {
return $this->model;
}
public function setEngine($engine) {
$this->engine = $engine;
}
public function getEngine() {
return $this->getEngine;
}
}
$car1 = new Car("Audi");
echo $car1->showCarDetails();