View Full Version : سوال: در زمینه class
se8820726
دوشنبه 06 آبان 1392, 14:29 عصر
سلام اقا من این نمونه کد رو دارم:
<?php
class test {
private $b;
function set($a) {
$this->b = $a;
return $this;
}
function get() {
return $this -> b;
}
}
$a = new test();
$a = $a -> set(10);
$b = $a -> set(20);
echo $a -> get();
echo $b -> get();
?>
حالا باید چه تغییراتی تو کلاسم بدم تا خروجیم تو خط هجده 10 بشه و تو خط نوزده 20 بشه ؟؟
MRmoon
دوشنبه 06 آبان 1392, 14:36 عصر
سلام اقا من این نمونه کد رو دارم:
<?php
class test {
private $b;
function set($a) {
$this->b = $a;
return $this;
}
function get() {
return $this -> b;
}
}
$a = new test();
$a = $a -> set(10);
$b = $a -> set(20);
echo $a -> get();
echo $b -> get();
?>
حالا باید چه تغییراتی تو کلاسم بدم تا خروجیم تو خط هجده 10 بشه و تو خط نوزده 20 بشه ؟؟
class test {
private $b;
function set($a) {
return new testb( $a );
}
}
class testb{
private $int;
function __construct( $int ){
$this -> int = $int;
}
function get( ){
return $this -> int;
}
}
$a = new test();
$b = $a -> set(10);
$c = $a -> set(20);
echo $b -> get();
echo $c -> get();
se8820726
دوشنبه 06 آبان 1392, 18:32 عصر
داداش من میخواستم که متد set از توی b$ و c$ هم قابل دسترس باشه.
الان نمونه زیر رو در نظر بگیر:
$test = '<div><p id="tagp"><a id="taga">text</a></p></div>';
$a = new DOMDocument();
$a -> loadHTML($test);
$tagp = $a -> getElementById('tagp');
echo $taga = $tagp -> getElementById('taga') -> nodeValue;
الان متد getElementById هم تو a$ در دسترس بود هم تو tagp$
چطوری یه همچین class ی درست کنیم ؟؟
MMSHFE
سه شنبه 07 آبان 1392, 09:07 صبح
<?php
class test {
private $b;
function set($a) {
$obj = new test();
$obj->b = $a;
return $obj;
}
function get() {
return $this->b;
}
}
$a = new test();
$b = $a->set(10);
$c = $a->set(20);
echo $b->get(); // output: 10
echo $c->get(); // output: 20
?>
دقت کنید که خروجی متد Set یک شئ جدید از خود کلاس اصلی هست. بنابراین متدهای Set و Get رو در اختیار شما میگذاره.
vBulletin® v4.2.5, Copyright ©2000-1403, Jelsoft Enterprises Ltd.